Skip to content

Instantly share code, notes, and snippets.

@gesquive
Last active June 22, 2023 16:50
Show Gist options
  • Save gesquive/c36501fbd84ecab00d3ff2c9502020f9 to your computer and use it in GitHub Desktop.
Save gesquive/c36501fbd84ecab00d3ff2c9502020f9 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
func main() {
var flagValue string
var cmdPing = &cobra.Command{
Use: "ping",
Short: "ping command",
Long: `ping command`,
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("ping called")
fmt.Printf("flag: %s\n", viper.GetString("flag"))
},
}
var cmdPong = &cobra.Command{
Use: "pong",
Short: "pong command",
Long: `pong command`,
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("pong called")
fmt.Printf("flag: %s\n", viper.GetString("flag"))
},
}
cmdPing.Flags().StringP("flag", "f", "", "testing flag")
cmdPong.Flags().StringP("flag", "f", "", "testing flag")
viper.BindPFlag("flag", cmdPing.Flags().Lookup("flag"))
viper.BindPFlag("flag", cmdPong.Flags().Lookup("flag"))
viper.SetDefault("flag", "")
var rootCmd = &cobra.Command{Use: "app"}
rootCmd.AddCommand(cmdPing, cmdPong)
rootCmd.Execute()
}
@gesquive
Copy link
Author

This is a well known workaround, not a fix. It doesn't fix the fact that you cannot configure the command with flags as intended. There is unintended behavior when you use the BindPFlag function as intended.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment