Cobra is a powerful CLI (Command Line Interface) library for Golang that provides a simple, yet powerful, interface for creating command line applications. It is known for its ease of use, powerful flag handling, and extensive documentation. This article will guide you through the process of creating a CLI application using Cobra in Golang.
Cobra is a library for creating powerful CLI applications with ease. It is built on top of the pflag
library, which is a fork of the Go flag package with POSIX compliance. Cobra has the following main features:
Before you can begin using Cobra, you must first install it. To do so, run the following command:
go get -u github.com/spf13/cobra/cobra
This will download and install the Cobra package and its dependencies to your $GOPATH
. Once the installation is complete, you can import Cobra into your Go projects.
To create a new CLI application, first create a new directory for your project:
mkdir my-cli-app && cd my-cli-app
Next, initialize your application by running the following command:
cobra init --pkg-name my-cli-app
This command will generate a basic Cobra application structure, including the following files:
LICENSE
: The license file for your applicationCommands are the core building blocks of a Cobra application. To create a new command, use the cobra add
command, followed by the name of the command:
cobra add mycommand
This will create a new file in the cmd
directory called mycommand., which contains the definition and behavior of the new command. You can customize the behavior of your command by editing the
Runfunction in the
mycommand. file:
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("Hello from mycommand!")
},
To add a subcommand to an existing command, simply provide the parent command as a prefix:
cobra add mycommand:myparentcommand
Cobra makes it easy to define and parse flags for your CLI commands. To define a flag, use the Flags()
function on your command object. Here’s an example of how to create a string flag called name
with a default value of "world"
:
mycommand.Flags().StringP("name", "n", "world", "Your name")
To access the value of a flag, use the GetString()
function from the cmd
package:
name, _ := cmd.Flags().GetString("name")
Now, you can use the name
variable in your command’s Run
function:
Run: func(cmd *cobra.Command, args []string) {
name, _ := cmd.Flags().GetString("name")
fmt.Printf("Hello, %s!\n", name)
},