package main import ( "fmt" "github.com/spf13/cobra" ) var rootCmd = &cobra.Command{ Use: "hello", Short: "Say hello to someone", Args: cobra.ExactArgs(1), Run: func(cmd *cobra.Command, args []string) { fmt.Printf("Hello %s!\n", args[0]) }, } func main() { if err := rootCmd.Execute(); err != nil { fmt.Println(err) os.Exit(1) } }
package main import ( "fmt" "github.com/spf13/cobra" ) var rootCmd = &cobra.Command{Use: "app"} var greetCmd = &cobra.Command{ Use: "greet", Short: "Greet someone", Args: cobra.ExactArgs(1), Run: func(cmd *cobra.Command, args []string) { fmt.Printf("Hello %s!\n", args[0]) }, } var goodbyeCmd = &cobra.Command{ Use: "goodbye", Short: "Say goodbye to someone", Args: cobra.ExactArgs(1), Run: func(cmd *cobra.Command, args []string) { fmt.Printf("Goodbye %s!\n", args[0]) }, } func init() { rootCmd.AddCommand(greetCmd) rootCmd.AddCommand(goodbyeCmd) } func main() { if err := rootCmd.Execute(); err != nil { fmt.Println(err) os.Exit(1) } }This code defines two sub-commands (greet and goodbye) that can be run under the main `app` command. Each sub-command takes one argument (the name of the person to greet or say goodbye to) and prints a message to the user. In summary, `github.com/spf13/cobra` is a powerful and flexible library for building command-line applications in Go. Its simple and intuitive API makes it easy to define and organize commands, sub-commands, and flags, while also providing a robust set of features and options for more complex use cases.