Cobra is a golang library for creating CLI applications and is using by Kubernetes, Hugo, and Github CLI..

Here we will show how to use cobra to build a CLI app.

Cobra command structure

Fellowing is Cobra command structure

APPNAME VERB NOUN --ADJECTIVE. or APPNAME COMMAND ARG --FLAG

Official document example is good for demonstration, ‘server’ is a command, and ‘port’ is a flag:

hugo server --port=1313

Here will demo how to use cobra build tools.

Init app

Create our app folder Init mytool project by mod package management:

mkdir mytool

cd mytool

go mod init mytool

Intall cobra generator

Here using Cobra Generator to create application and command.

Install cobra generator into our $GOPATH/bin directory:

go get github.com/spf13/cobra/cobra

Init cobra app

Init first command-line application:

cobra init --pkg-name mytool


//will output fellowing message when init finished
Your Cobra application is ready at

File & folder tree will like fellowing:

.
├── LICENSE
├── cmd
│   └── root.go
└── main.go

1 directory, 3 files

Setting command-line tool informations

In the cmd/root.go file, include fellowing info, can define tools command (Use), short descriptions(Short), and long descriptions(Long):

In rootCmd command, Run function is a default action when execute app:

package cmd

import (
	"fmt"
	"os"
	"github.com/spf13/cobra"

	homedir "github.com/mitchellh/go-homedir"
	"github.com/spf13/viper"
)

var cfgFile string

// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
	Use:   "mytool",
	Short: "A brief description of your application",
	Long: `A longer description that spans multiple lines and likely contains
examples and usage of using your application. For example:

Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.`,
	// Uncomment the following line if your bare application
	// has an action associated with it:
	Run: func(cmd *cobra.Command, args []string) {
        fmt.Println("Welcome to my tools")
    },
}
...

Build and execute app

Build our app

go build main.go

Execute out app

./mytool

The fellowing message will be output:

Welcome to my tools

Create command

Create command, the camelCase is recommended, and create rule is:

cobra add {commandName}

Here create a command to show Helloworld:

cobra add showHelloWorld

Command file will auto-generated in cmd/showHelloWorld.go, and default Run will print “showHelloWorld called”

	Run: func(cmd *cobra.Command, args []string) {
		fmt.Println("showHelloWorld called")
	},

Rebuild app and execute will showing output wording:

go build mail.go

./mytool showHelloWorld

Cobra Flags - Transfer arguements

Cobra can use flags to transfer arguments to commands.

Here we demo a wording lower and upper mode:

Create a word command:

cobra add word

Open cmd/word.go and setting a string and mode flags

...
var wordCmd = &cobra.Command{
	Use:   "word",
	Short: "A brief description of your command",
	Long: `A longer description.`,
	Run: func(cmd *cobra.Command, args []string) {
		var result string
		switch mode {
		case "lower":
			result = strings.ToLower(str)
		case "upper":
			result = strings.ToUpper(str)
		default:
			result = "please input mode"
		}
		fmt.Printf(result)
	},
}
var str, mode string

func init() {
	rootCmd.AddCommand(wordCmd)
	wordCmd.Flags().StringVar(&str, "string", "default string", "input your wording")
	wordCmd.Flags().StringVar(&mode, "mode", "lower", "choose mode like upper, lower")
}

Finally, build an app and run following command for transfer flags:

./mytool word --string="hEllO WorLd" --mode=lower
./mytool word --string="hEllO WorLd" --mode=upper

Questions

Why cobra init not work?

You can try to explore go path, or execute cobra directory:

// checking your go path is corrected
export PATH="~/go/bin:$PATH"

//or execute cobra directory

~/go/bin/cobra init --pkg-name mytools