How to Use Cobra for Building CLIs in Go

Cli
Use the Cobra CLI generator to scaffold a Go project and define commands in main.go to build a functional command-line interface.

Use the cobra CLI generator to scaffold your project, then define commands and flags in your main.go file.

  1. Install the generator tool. go install github.com/spf13/cobra/cobra@latest

  2. Generate the initial project structure. cobra init myapp

  3. Add a subcommand to your application. cobra add mycommand

  4. 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)
	}
}