Use the cobra CLI generator to scaffold your project, then define commands and flags in your main.go file.
-
Install the generator tool.
go install github.com/spf13/cobra/cobra@latest -
Generate the initial project structure.
cobra init myapp -
Add a subcommand to your application.
cobra add mycommand -
Run your application to verify the setup.
go run main.go
package main
import (
"fmt"
"github.com/spf13/cobra"
)
var rootCmd = &cobra.Command{
Use: "myapp",
Short: "A brief description of your application",
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("Hello, World!")
},
}
func main() {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
}
}