Working with Cobra - The Root Command

In this lesson, you'll learn how to get started with Cobra as a library and define the root command for a simple calculator application.

We'll cover the following

Defining the root command

Our starting point is an application with a package for doing calculations. Here is the directory structure:

$ tree
.
├── go.mod
├── go.sum
└── pkg
    └── calc
        └── calc.go

As you can see, there is just the pkg directory with the calc package inside it. There isn’t even a main package yet.

The first step is to define a Cobra root command. This command is always executed when the program is invoked, and it may delegate the actual work to subcommands. We will create our commands in a top-level directory called cmd. The root command will be in its own file called cmd/root.go.

Let’s break it down piece by piece. First, we declare the package as cmd and add some imports, most notably Cobra itself:

package cmd

import (
	"fmt"
	"os"

	"github.com/spf13/cobra"
)

Then, we initiate the command itself as a cobra.Command. We provide several arguments to describe the command. We can also declare a Run function that will execute when no sub-commands are provided. However, in this case we leave it without comments out, so subcommands are required.

var rootCmd = &cobra.Command{
	Use:   "calc",
	Short: "Calculate arithmetic expressions",
	Long: `Calculate arithmetic expressions.
           
           It can add integers and subtract integers`,
	// Uncomment the following line if you want the root command
	// to perform some action
	//	Run: func(cmd *cobra.Command, args []string) { },
}

The reason for this decision is that there is no useful calculation we can do without additional add or subtract subcommands.

You can explore and run the calc app in the application below. Please set the GO111Module to on to run the following applications.

Get hands-on with 1200+ tech skills courses.