The Cobra CLI library is a powerful tool for building command-line interfaces (CLIs) in Go, providing a robust framework that simplifies the creation of complex applications. This tutorial will walk you through the process of creating a basic CLI application using Cobra, including setting up your environment, defining commands, and handling flags.
Before we dive into the tutorial, ensure you have the following installed:
To get started with Cobra, you need to install it using go get. Open your terminal and run the following command:
go get -u github.com/spf13/cobra/cobra
This command installs the Cobra CLI tool, which you can use to generate new Cobra projects.
To create a new project, navigate to your desired directory and run:
cobra init my-cli-app --pkgname=my-cli-app
This command initializes a new Cobra project named my-cli-app with the specified package name. The --pkgname flag is optional but recommended for clarity.
After running the above command, you'll see the following directory structure:
my-cli-app/
āāā cmd/
ā āāā root.go
āāā main.go
āāā go.mod
Cobra uses a hierarchical command structure, where commands can have subcommands. Let's start by defining a simple hello command that prints "Hello, World!".
Inside the cmd directory, create a new file named hello.go.
package cmd
import (
"fmt"
"github.com/spf13/cobra"
)
var helloCmd = &cobra.Command{
Use: "hello",
Short: "Prints 'Hello, World!'",
Long: "A longer description that spans multiple lines and likely contains examples and usage of using your command.",
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("Hello, World!")
},
}
func init() {
rootCmd.AddCommand(helloCmd)
}
In cmd/root.go, you'll see that the helloCmd is already registered to the root command. This is done by calling rootCmd.AddCommand(helloCmd) in the init function.
Now, let's run your CLI application to see the new command in action. First, build your application:
go build -o my-cli-app
Then, execute the binary:
./my-cli-app hello
You should see the output:
Hello, World!
Flags are a common way to pass options and arguments to CLI commands. Cobra makes it easy to define and handle flags.
Let's add a --name flag to our hello command that allows users to specify a name.
Modify cmd/hello.go as follows:
package cmd
import (
"fmt"
"github.com/spf13/cobra"
)
var helloCmd = &cobra.Command{
Use: "hello",
Short: "Prints 'Hello, World!'",
Long: "A longer description that spans multiple lines and likely contains examples and usage of using your command.",
Run: func(cmd *cobra.Command, args []string) {
name, _ := cmd.Flags().GetString("name")
if name != "" {
fmt.Printf("Hello, %s!\n", name)
} else {
fmt.Println("Hello, World!")
}
},
}
var name string
func init() {
helloCmd.Flags().StringVarP(&name, "name", "n", "", "Name to greet")
rootCmd.AddCommand(helloCmd)
}
Now, you can run your CLI with the --name flag:
./my-cli-app hello --name=Qwen
You should see the output:
Hello, Qwen!
cmd directory.Short and Long fields.Cobra is a versatile library that simplifies the process of building robust CLI applications in Go. By following this tutorial, you've learned how to set up a basic CLI project, define commands, handle flags, and apply best practices. As you continue to develop your application, consider exploring additional features such as persistent flags, command aliases, and subcommands.
With Cobra, the possibilities for creating powerful and user-friendly CLIs are endless. Happy coding!