var rootCmd = &cobra.Command{ Use: "mycli", Short: "A brief description of your CLI tool", Long: "A longer description of your CLI tool", // Define a flag for the CLI tool Flags: []cli.Flag{ &cli.StringFlag{ Name: "config", Usage: "config file to use", }, }, Run: func(cmd *cobra.Command, args []string) { // main command logic goes here }, }
var rootCmd = &cobra.Command{ // ... // Add a subcommand to the CLI tool // The subcommand can have its own flags and arguments // and will execute its own Run function Commands: []*cobra.Command{ &cobra.Command{ Use: "subcmd", Short: "A brief description of your subcommand", Long: "A longer description of your subcommand", Args: cobra.MinimumNArgs(1), // Define a flag for the subcommand Flags: []cli.Flag{ &cli.BoolFlag{ Name: "verbose", Usage: "verbose output", }, }, Run: func(cmd *cobra.Command, args []string) { // subcommand logic goes here }, }, }, }
func main() { if err := rootCmd.Execute(); err != nil { fmt.Fprintf(os.Stderr, "Error: %v\n", err) os.Exit(1) } }In conclusion, `cobra` is a powerful Go package for creating command-line interfaces. It provides a simple yet flexible API for creating CLI applications with subcommands, flags, and arguments.