This (everything in the main.go
) works
var rootCmd = &cobra.Command{
Use: "myapp",
Short: "Myapp",
PreRunE: func(cmd *cobra.Command, args []string) error {
fmt.Println("binding variables")
if err := viper.BindPFlags(cmd.Flags()); err != nil {
return err
}
fmt.Println(viper.GetString("allow-origin"))
return nil
},
RunE: func(cmd *cobra.Command, args []string) error {
return viper.BindPFlags(cmd.Flags())
},
}
func main() {
rootCmd.PersistentFlags().StringP("allow-origin", "", "", "help")
rootCmd.Execute()
▶ go run web/main.go myapp --allow-origin https://111.222.33.4
binding variables
https://111.222.33.4
THIS, where the definition of the rootCmd
and the flag addition has been moved to another package (cmd
) does not work
package main
func main() {
cmd.RootCmd.PersistentFlags().StringP("allow-origin", "", "", "help")
cmd.RootCmd.Execute()
package cmd
var RootCmd = &cobra.Command{
Use: "myapp",
Short: "Myapp",
PreRunE: func(cmd *cobra.Command, args []string) error {
fmt.Println("binding variables")
if err := viper.BindPFlags(cmd.Flags()); err != nil {
return err
}
fmt.Println(viper.GetString("allow-origin"))
return nil
},
RunE: func(cmd *cobra.Command, args []string) error {
return viper.BindPFlags(cmd.Flags())
},
}
▶ go run web/main.go myapp --allow-origin https://111.222.33.4
binding variables
i.e. in the second case, the flag allow-origin
is not bound (!)
What am I missing?