var myCmd = &cobra.Command{ Use: "mycmd", Short: "My command", Long: "A brief description of my command", Run: func(cmd *cobra.Command, args []string) { // Run command logic here fmt.Println("Hello, " + name) }, } var name string func init() { myCmd.Flags().StringVarP(&name, "name", "n", "World", "Greetings name") }
var myCmd = &cobra.Command{ Use: "mycmd", Short: "My command", Long: "A brief description of my command", Run: func(cmd *cobra.Command, args []string) { // Run command logic here if verbose { fmt.Println("Verbose output enabled") } }, } var verbose bool func init() { myCmd.Flags().BoolVarP(&verbose, "verbose", "v", false, "Enable verbose output") }
type myflag struct { Value bool Usage string } func (f *myflag) String() string { return fmt.Sprintf("%t", f.Value) } func (f *myflag) Set(value string) error { parsed, err := strconv.ParseBool(value) if err != nil { return err } f.Value = parsed return nil } var myCmd = &cobra.Command{ Use: "mycmd", Short: "My command", Long: "A brief description of my command", Run: func(cmd *cobra.Command, args []string) { // Run command logic here if myflag.Value { fmt.Println("Custom flag enabled") } }, } var myflag = myflag{ Usage: "Enable custom flag", } func init() { myCmd.Flags().VarP(&myflag, "myflag", "m", myflag.Usage) }In this example, we define a custom flag type that implements the `flag.Value` interface. This allows us to define custom parsing logic for our flag value. We then use the `VarP` function to add our custom flag to the command. The flag will be accessible via the `myflag` variable.