package main import ( "fmt" "github.com/spf13/cobra" ) func main() { rootCmd := &cobra.Command{ Use: "my-app", Short: "Simple CLI app", Long: `This is a simple command-line app written in Go.`, } cmdHello := &cobra.Command{ Use: "hello [name]", Short: "Say hello to someone", Args: cobra.MaximumNArgs(1), Run: func(cmd *cobra.Command, args []string) { if len(args) > 0 { fmt.Printf("Hello, %s!\n", args[0]) } else { fmt.Println("Hello, world!") } }, } rootCmd.AddCommand(cmdHello) rootCmd.Execute() }
var rootCmd = &cobra.Command{ Use: "my-app", Short: "Simple CLI app", } var cmdHello = &cobra.Command{ Use: "hello [name]", Short: "Say hello to someone", Args: cobra.ExactArgs(1), Run: func(cmd *cobra.Command, args []string) { fmt.Printf("Hello, %s!\n", args[0]) }, } func init() { rootCmd.AddCommand(cmdHello) } func main() { if err := rootCmd.Execute(); err != nil { fmt.Println(err) os.Exit(1) } }In this example, we use the `ExactArgs` function instead of `MaximumNArgs` to specify that the command requires exactly one argument. We also use the `init` function to add the subcommand to the root command. Overall, go github.com/spf13.cobra is a powerful package library for building CLI applications with Go, and Command Usage is a useful feature for defining how your application should be used.