package main import ( "fmt" "github.com/appc/acbuild/godeps/_workspace/src/github.com/spf13/cobra" ) func main() { rootCmd := &cobra.Command{ Use: "hello", Short: "Prints 'hello world' to the console", Run: func(cmd *cobra.Command, args []string) { fmt.Println("hello world") }, } if err := rootCmd.Execute(); err != nil { fmt.Println(err) os.Exit(1) } }
package main import ( "fmt" "github.com/appc/acbuild/godeps/_workspace/src/github.com/spf13/cobra" ) func main() { rootCmd := &cobra.Command{Use: "myapp"} subCmd := &cobra.Command{ Use: "add", Short: "Adds two numbers together", Run: func(cmd *cobra.Command, args []string) { num1, _ := cmd.Flags().GetInt("num1") num2, _ := cmd.Flags().GetInt("num2") sum := num1 + num2 fmt.Printf("%d + %d = %d\n", num1, num2, sum) }, } subCmd.Flags().Int("num1", 0, "The first number") subCmd.Flags().Int("num2", 0, "The second number") rootCmd.AddCommand(subCmd) if err := rootCmd.Execute(); err != nil { fmt.Println(err) os.Exit(1) } }In this example, the `myapp` command has a sub-command called `add`. The `add` sub-command takes two integer arguments, `num1` and `num2`, and adds them together. The `GetInt` method is used to retrieve the values of the `num1` and `num2` flags, and the `Run` function performs the addition and prints the result to the console. Overall, cobra provides a flexible and user-friendly way to create command-line interfaces in Go. It simplifies the process of parsing command-line arguments and allows developers to define complex CLI structures with ease.