November 25th, 2017

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 nodeskubectl create -f ...RESOURCEkubectl delete -f ...RESOURCE
Create sub-command using Cobra
Take those command as an example, there are some sub-command as follow:
getcreatedelete
Here is how we add that sub-command to your app. (ex: kctl)
cobra initin your repo. It will create/cmdandmain.go.cobra add getto add sub-command get- now, you can try
kctl getto get prompt from the console which you already call this sub-command.
- now, you can try
- Repeatedly for
createanddelete. You will see related help inkctl --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.goin/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).