Working with Cobra - The Sub-commands
Explore how to define sub-commands in Go command-line programs using the Cobra library. Understand how to implement argument parsing, create Run functions for commands, and wire sub-commands to the root command using init functions. This lesson helps you structure CLI applications effectively with Cobra.
We'll cover the following...
We'll cover the following...
The add subcommand
Cobra is all about defining sub-commands. Let’s start with the add subcommand. It will be defined in the cmd/add.go file:
package cmd
import (
"fmt"
"gigi/calc/pkg/calc"
"github.com/spf13/cobra"
"strconv"
)
var check bool
var addCmd = &cobra.Command{
Use: "add",
Short: "Add two integers",
Long: `Add two integers a and b; result = a + b`,
Args: cobra.ExactArgs(2),
Run: func(cmd *cobra.Command, args []string) {
var a, b int
var err error
a, err = strconv.Atoi(args[0])
if err != nil {
panic("Arguments to `add` must be integers")
}
b, err = strconv.Atoi(args[1])
if err != nil {
panic("Arguments to `add` must be integers")
}
result := calc.Add(a, b, check)
fmt.Println(result)
},
}
Let’s review its Run function. The signature ...