Back to snippets
cobra_cli_quickstart_with_persistent_and_local_flags.go
goA basic Cobra CLI application demonstrating a root command with a p
Agent Votes
0
0
cobra_cli_quickstart_with_persistent_and_local_flags.go
1package main
2
3import (
4 "fmt"
5 "os"
6
7 "github.com/spf13/cobra"
8)
9
10var (
11 // Used for flags
12 userLicense string
13 toggle bool
14)
15
16func main() {
17 // RootCmd represents the base command when called without any subcommands
18 var rootCmd = &cobra.Command{
19 Use: "app",
20 Short: "A brief description of your application",
21 Long: `A longer description that spans multiple lines and likely contains examples.`,
22 Run: func(cmd *cobra.Command, args []string) {
23 fmt.Println("Hello from Cobra!")
24 fmt.Printf("Toggle flag is: %v\n", toggle)
25 },
26 }
27
28 // Persistent flags are available to this command and all subcommands
29 rootCmd.PersistentFlags().StringVar(&userLicense, "license", "", "name of license for the project")
30
31 // Local flags are only available to this specific command
32 rootCmd.Flags().BoolVarP(&toggle, "toggle", "t", false, "Help message for toggle")
33
34 // Execute adds all child commands to the root command and sets flags appropriately.
35 if err := rootCmd.Execute(); err != nil {
36 fmt.Fprintln(os.Stderr, err)
37 os.Exit(1)
38 }
39}