spf13/cobra is a great package if you want to write your own console app. Even Kubernetes console use cobra to develop it console app.

Create simple CLI app example.

Let’s use kubectl as simple example it support.

  • kubectl get nodes
  • kubectl create -f ...RESOURCE
  • kubectl delete -f ...RESOURCE

Create sub-command using Cobra

Take those command as an example, there are some sub-command as follow:

  • get
  • create
  • delete

Here is how we add that sub-command to your app. (ex: kctl)

  • cobra init in your repo. It will create /cmd and main.go.
  • cobra add get to add sub-command get
    • now, you can try kctl get to get prompt from the console which you already call this sub-command.
  • Repeatedly for create and delete. You will see related help in kctl --help.

Add nested-command using Cobra

Cobra could use console mode to add sub-command, but you need to add nested command manually.

ex: we need add one for kctl get nodes.

  • Add nodes.go in /cmd
  • Add following code as an example.
package cmd

import (
  "fmt"

  "github.com/spf13/cobra"
)

func init() {
  getCmd.AddCommand(nodesCmd)
}

var nodesCmd = &cobra.Command{
  Use:   "nodes",
  Short: "Print the nodes info",
  Long:  `All software has versions. This is Hugo's`,
  Run: func(cmd *cobra.Command, args []string) {
    fmt.Println("get nodes is call")
  },
}
  • The most important you need getCmd.AddCommand(nodesCmd).

Buy Me A Coffee

Evan

Attitude is everything