Problem Statement
Build a professional CLI application using Cobra, the framework behind kubectl, docker, and hugo.
Build a professional CLI application using Cobra, the framework behind kubectl, docker, and hugo.
mycli/
├── cmd/
│ ├── root.go
│ ├── serve.go
│ └── migrate.go
├── main.go
└── go.modpackage main
import "mycli/cmd"
func main() {
cmd.Execute()
}package cmd
import (
"fmt"
"os"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
var (
cfgFile string
verbose bool
)
var rootCmd = &cobra.Command{
Use: "mycli",
Short: "My awesome CLI application",
Long: `A longer description that spans multiple lines.`,
}
func Execute() {
if err := rootCmd.Execute(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func init() {
cobra.OnInitialize(initConfig)
// Persistent flags (available to all subcommands)
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "",
"config file (default $HOME/.mycli.yaml)")
rootCmd.PersistentFlags().BoolVarP(&verbose, "verbose", "v", false,
"verbose output")
viper.BindPFlag("verbose", rootCmd.PersistentFlags().Lookup("verbose"))
}
func initConfig() {
if cfgFile != "" {
viper.SetConfigFile(cfgFile)
} else {
home, _ := os.UserHomeDir()
viper.AddConfigPath(home)
viper.SetConfigName(".mycli")
}
viper.AutomaticEnv()
viper.ReadInConfig()
}package cmd
import (
"fmt"
"github.com/spf13/cobra"
)
var (
port int
host string
)
var serveCmd = &cobra.Command{
Use: "serve",
Short: "Start the server",
Long: "Start the HTTP server with specified configuration",
Run: func(cmd *cobra.Command, args []string) {
fmt.Printf("Starting server on %s:%d\n", host, port)
// Start server...
},
}
func init() {
rootCmd.AddCommand(serveCmd)
serveCmd.Flags().IntVarP(&port, "port", "p", 8080, "Port to listen on")
serveCmd.Flags().StringVar(&host, "host", "0.0.0.0", "Host to bind to")
// Mark flag as required
serveCmd.MarkFlagRequired("port")
}var mathCmd = &cobra.Command{
Use: "math",
Short: "Mathematical operations",
}
var addCmd = &cobra.Command{
Use: "add [numbers...]",
Short: "Add numbers together",
Args: cobra.MinimumNArgs(2),
Run: func(cmd *cobra.Command, args []string) {
sum := 0
for _, arg := range args {
n, _ := strconv.Atoi(arg)
sum += n
}
fmt.Printf("Sum: %d\n", sum)
},
}
func init() {
rootCmd.AddCommand(mathCmd)
mathCmd.AddCommand(addCmd)
}
// Usage: mycli math add 1 2 3 4
// Output: Sum: 10import "github.com/spf13/cobra/doc"
// Generate Markdown docs
doc.GenMarkdownTree(rootCmd, "./docs")
// Generate man pages
doc.GenManTree(rootCmd, nil, "./man")