var rootCmd = &cobra.Command{ Use: "myapp", Short: "My awesome app", PersistentPreRun: func(cmd *cobra.Command, args []string) { // do something before running each sub-command }, } func init() { rootCmd.PersistentFlags().StringVarP(&database, "database", "d", "localhost", "Database connection string") }
var createUserCmd = &cobra.Command{ Use: "create-user", Short: "Create a new user", Run: func(cmd *cobra.Command, args []string) { fmt.Println("Database connection string:", database) // do something here }, } func init() { // inherit parent command's persistent flag(s) rootCmd.AddCommand(createUserCmd) createUserCmd.Flags().StringVar(&username, "username", "admin", "Username for the new user") createUserCmd.Flags().StringVar(&password, "password", "", "Password for the new user") }In this example, we access the `database` flag defined in the previous example and print its value in the `Run` function of the `createUserCmd` sub-command. We also define two local flags, `username` and `password`, which are specific to the `createUserCmd` sub-command. Overall, `github.com/spf13/cobra` provides a powerful and flexible framework for creating command-line applications in Go. The `PersistentFlags` feature allows for easy management of global flags, which can greatly simplify the development of complex command-line tools.