package main import ( "fmt" "github.com/spf13/cobra" ) var rootCmd = &cobra.Command{ Use: "myapp", Short: "My app does things", Long: `A longer description of what my app does.`, Run: func(cmd *cobra.Command, args []string) { fmt.Println("Hello, world!") }, } func main() { rootCmd.Execute() }
package main import ( "fmt" "github.com/spf13/cobra" ) func main() { var name string var rootCmd = &cobra.Command{ Use: "myapp", Short: "My app does things", Long: `A longer description of what my app does.`, } var helloCmd = &cobra.Command{ Use: "hello", Short: "Say hello to someone", Long: `Say hello to someone by name.`, Run: func(cmd *cobra.Command, args []string) { fmt.Printf("Hello, %s!\n", name) }, } helloCmd.Flags().StringVarP(&name, "name", "n", "world", "Name of the person to say hello to.") rootCmd.AddCommand(helloCmd) rootCmd.Execute() }This example defines a CLI application called "myapp" that has one command called "hello". The "hello" command takes a name argument, and prints "Hello, {name}!" to the console. The example demonstrates the use of command line flags in cobra, by allowing the user to specify the name of the person to say hello to using the `-n` or `--name` flag.