Introduction
The Cobra package is a renowned library in Go for building powerful, modern command line applications (CLIs). It finds use in many notable Go projects such as Kubernetes, Hugo, and GitHub CLI, proving its effectiveness and popularity 1 . This tutorial will walk you through the basic steps to get started with Cobra in Go, including installing the package, creating commands and subcommands, adding flags to commands, and organizing the code in a Cobra-based application.
Package Installation:
Install the Cobra package using the following command:
go get -u github.com/spf13/cobra
Import the Cobra package into your application:
import "github.com/spf13/cobra"
Structure of a Cobra Application: A typical Cobra-based application will have a directory structure similar to this:
appName/cmd/add.go
your.go
commands.go
here.go
main.go
In your project, the cmd
directory will contain all your commands and subcommands, while the main.go
file will serve as the entry point for your application 3 .
Creating Commands and Subcommands:
- Commands represent actions, while flags are modifiers for those actions. For example, in
go run test.go --port=1123
, 'run' is a command and 'port' is a flag. - Creating a new command is simple with Cobra. Start by creating a new Go file in the
cmd
directory with the name of your command (e.g.,add.go
). - Inside this file, define your command as a variable of type
*cobra.Command
.
var addCmd = &cobra.Command{
Use: "add",
Short: "Add a new item",
Long: `Add a new item to the list.`,
Run: func(cmd *cobra.Command, args []string) {
//Il tuo codice qui
},
}
Add your command to the application root command in your main.go
file:
func main() {
rootCmd.AddCommand(addCmd)
rootCmd.Execute()
}
Conclusion
With Cobra, building robust and organized CLI applications in Go is a relatively simple task. By following this tutorial, you should now have a solid understanding of how to get started with Cobra, create commands and subcommands, and organize your code in a Cobra-based application. Continuous exploration of Cobra documentation and hands-on implementation will help you become more proficient in using this powerful library.