What is Cobra?
Cobra is a powerful library and tool in Golang used to create CLI (Command-Line Interface) applications. Cobra does this by providing tools that automate the process and provide key abstractions that increase developer productivity.
Why use Cobra?
Among the many benefits of using Cobra, here are some to consider:
- Easy to create subcommand-based CLIs and use nested subcommands.
- Automatic help generation for commands and flags.
- Increased productivity because of commands such as
cobra init appname&cobra add cmdname. - Helpful, intelligent suggestions (
app srver… did you meanapp server?).
Installing
To use Cobra, you need to use go get to install the library’s latest version. This command will install the cobra generator executable along with the library and its dependencies:
go get github.com/spf13/cobra/cobra
Next, include Cobra in your application:
import "github.com/spf13/cobra"
Using cobra
Initialize your Cobra CLI app with the cobra init --pkg-name <app> command. This command will construct the basic application structure for you.
You can add commands to your application with the cobra add <commandName> syntax.
Cobra warns against the use of snake_case/snake-case because it may lead to errors. Instead, use camelCase.
Design
In order to use Cobra, a user must define a structure with a name, description, and function to run the logic. Look at code below:
cmd := &cobra.Command{
// cobra name
Run: Hello,
// identifier
Use: `hello`,
Short: "GreetUser",
// what this command should print
Long: "This command will print Hello World",
}
This design is quite similar to the native Go commands (like go env, go fmt, etc.) in the standard library.
For further understanding of how to use cobra, click here.
Free Resources