Using Cobra for Advanced CLI Applications
Learn how to use Cobra for advanced CLI applications in Go.
We'll cover the following...
Cobra is a set of packages that allows a developer to create more complex CLI applications. This becomes more useful than just the standard flag
package when the complexity of an application causes a list of flags to become numerous.
In this lesson, we’ll talk about how to use Cobra to create structured CLI applications that are friendly to developers to add features and allow users to understand what is available in an application.
A few features that Cobra provides are as follows:
Nested subcommands
Command suggestions
Aliases for commands so that we can make changes without breaking users
Generation of help text from flags and commands
Generation of auto-completion for various shells
Man page creation
This section will borrow heavily from the Cobra documentation, which you can find here.
Code organization
To make effective use of Cobra and make it easy for developers to understand where to add and change commands, Cobra suggests the following structure:
appName/cmd/add.goyour.gocommands.gohere.gomain.go
This structure has our main main.go
executable at the top-level directory and all of our commands under cmd/
.
The main file for a Cobra application is primarily used to simply initialize Cobra and let it perform command executions. The file will look like this:
package mainimport ("{pathToYourApp}/cmd")func main() {cmd.Execute()}
Next, we'll look at ...