This tutorial aims to educate you on how to use the Cobra library to build interactive Command Line Interface (CLI) applications using Go. We will learn how to create commands, subcommands, and add flags to our commands using Cobra.
By the end of this tutorial, you will be able to:
Prerequisites:
- Basic knowledge of Go programming
- Go installed on your system
Cobra is a library that provides a simple interface to create powerful modern CLI interfaces, similar to git & go tools. Cobra is also an application that will generate your application scaffolding to rapidly develop a Cobra-based application.
In this guide, we will start by installing Cobra, creating a new project, and then creating our commands.
go get -u github.com/spf13/cobra/cobra
mkdir mycli && cd mycli
cobra init --pkg-name mycli
This will create a new Cobra application.
Commands represent actions. In cobra
, we can create a new command using cobra.Command
.
var cmd = &cobra.Command{
Use: "command_name",
Short: "Short description of the command",
Long: `Long description of the command`,
Run: func(cmd *cobra.Command, args []string) {
// Do Stuff Here
},
}
Let's create a hello
command for our CLI app.
var helloCmd = &cobra.Command{
Use: "hello",
Short: "Prints out 'Hello, World!'",
Long: `A command to print out 'Hello, World!'`,
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("Hello, World!")
},
}
func init() {
rootCmd.AddCommand(helloCmd)
}
In the above code:
- helloCmd
is the command we are creating
- Use
is the name of the command
- Short
and Long
are the descriptions of the command
- Run
is the function that gets executed when the command is called
- rootCmd.AddCommand(helloCmd)
adds the hello
command to the root command
When you run your cli app with the hello
command, it prints out Hello, World!
.
In this tutorial, we learned about the Cobra library, how to create a new Cobra application, and how to create commands. We also saw a code example of creating a hello
command.
Next, you can learn about creating subcommands, adding flags to commands, and more. Refer to the Cobra Documentation for more information.
goodbye
command that prints out Goodbye, World!
greet
command that takes in a name as a flag and prints out Hello, [name]!
goodbye
command:var goodbyeCmd = &cobra.Command{
Use: "goodbye",
Short: "Prints out 'Goodbye, World!'",
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("Goodbye, World!")
},
}
func init() {
rootCmd.AddCommand(goodbyeCmd)
}
greet
command:var name string
var greetCmd = &cobra.Command{
Use: "greet",
Short: "Greets a user",
Run: func(cmd *cobra.Command, args []string) {
fmt.Printf("Hello, %s!\n", name)
},
}
func init() {
greetCmd.Flags().StringVarP(&name, "name", "n", "", "Name to greet")
rootCmd.AddCommand(greetCmd)
}
In the greet
command, we added a name
flag using greetCmd.Flags().StringVarP()
. This allows us to pass in a name when calling the greet
command.