a shot of dev knowledge

RELATED TAGS

How to use Cobra in Golang

Cobra is a powerful library and tool in Golang that is used to create CLI (Command-Line Interface) applications. Cobra does this by providing tools that automate the process and provide key abstractions that increase developer productivity.

svg viewer

Why use Cobra?

Among the many benefits of using Cobra, here are some to consider:

  • Easy to create subcommand-based CLIs and use nested subcommands.
  • Automatic help generation for commands and flags.
  • Increased productivity because of commands such as cobra init appname & cobra add cmdname.
  • Helpful, intelligent suggestions (app srver… did you mean app server?).

Installing

To use Cobra, you need to use go get to install the latest version of the library. This command will install the cobra generator executable along with the library and its dependencies:

go get github.com/spf13/cobra/cobra

Next, include Cobra in your application:

import "github.com/spf13/cobra"

Using cobra

Initialize your Cobra CLI app with the cobra init --pkg-name <app> command. This command will construct the basic application structure for you.

You can add commands to your application with the cobra add <commandName> syntax.

Cobra warns against the use of snake_case/snake-case because that may lead to errors. Instead, use camelCase.

Your directory will look like this:

svg viewer

Implementation

Let’s look at a simple use case for Cobra. In the code below, we will create a simple CLI application to make additions.

For this implementation, we will have three files:

File Directory
1. main.go app/demo
2. root.go app/demo/cmd
3. add.go app/demo/cmd

To initialize your CLI application, write the following command in your terminal:

cobra init --pkg-name demo

This will create your main.go and root.go files. Your main.go is our entry point to our Cobra application and is usually just:

package main

import (
  "{pathToYourApp}/cmd"
)

func main() {
  cmd.Execute()
}

The significant bit in the root.go file is below (you can ignore the rest of the code for now):

var rootCmd = &cobra.Command{
  Use:   "demo",
  Short: "demo app to demonstrate cobra",
  Long: `demo app to demonstrate cobra by addition`
}

func Execute() {
  if err := rootCmd.Execute(); err != nil {
    fmt.Println(err)
    os.Exit(1)
  }
}

Now, add the ‘add’ command by writing:

cobra add add

This will create a file for our “add” command. The code for the file is:

package cmd

import (
	"fmt"
	"strconv"
	"github.com/spf13/cobra"
)

// addCmd represents the add command
var addCmd = &cobra.Command{
	Use:   "add",
	Short: "add values passed to function",
	Long: `Demo application to demonstrate cobra featues`,
	Run: func(cmd *cobra.Command, args []string) {
		sum := 0
		for _ , args := range args {
			num, err :=  strconv.Atoi(args)
		
		if err != nil {
			fmt.Println(err)
		}
		sum = sum + num
	}
		fmt.Println("result of addition is", sum)
	},
}

func init() {
	rootCmd.AddCommand(add)
}


You can execute the program by running:

go install

followed by:

demo add 1 2 3

for which the output would be:

result of addition is 6

Visit the github page for more information.

RELATED TAGS

RELATED COURSES

View all Courses

Keep Exploring