Introduction
Unlike Node.js, where a project already comes with the npm CLI and script handling via package.json, Go projects don’t have a built‑in CLI for scripting. Instead, they rely on external adapters. Today I learned how to use Cobra CLI to handle this, and I’ll walk you through the basics.
Installing Cobra CLI
First, install Cobra CLI with:
go get -u github.com/spf13/cobra@latest && \
go install github.com/spf13/cobra-cli@latest
Initializing Your Project
Run:
cobra-cli init
This command generates a main.go file and a cmd folder containing a root.go file. The root.go file is where core CLI configurations are set up. You can also use this file for essential initialisations; for example, in my study case, I initialised the database connection within my project.
Creating Your Own Command
To create a new, custom command for your application, use the add command:
cobra-cli add NAME-OF-COMMAND
If I use cli as the name, Cobra generates a new file (e.g., cli.go). This file includes basic description information that you can modify as needed.
Defining Logic and Flags
Inside the generated command file (e.g., cli.go), I need to declare the variables that my function requires.
In the generated init function, I create the flags that my command can receive and associate each flag's value with a variable.
// Example of flag creation in the `init` function
func init() {
// ... other code ...
// Define flags and bind them to variables
cliCmd.Flags().StringVarP(&action, "action", "a", "read", "Action to perform (create/read/update/delete)")
cliCmd.Flags().StringVarP(&productName, "product", "p", "", "Name of the product")
cliCmd.Flags().Float32VarP(&productPrice, "price", "r", 0.0, "Price of the product")
}
// Example of command execution in the Run function
func run(cmd *cobra.Command, args []string) {
// Logic goes here
fmt.Printf("Action: %s, Product: %s, Price: %.2f\n", action, productName, productPrice)
// In a real app, this would call a function to interact with the database
}
Then, if I run the following command:
go run main.go cli -action=create -product=Produto -price=25.0
I am assigning values to the variables (action, productName, and productPrice), and the Run function can then use them to, for example, create a new product in the database.
Top comments (0)