1

I'm working on a Cobra-based app in Go and for one of my commands I'm defining a flag like this:

func init() {
    myCmd.Flags().StringVarP(&project, "project", "p", "defaultProject", "Project name")
}

I also have a Viper set up in my root command that reads some configuration from a file. Is there a way to set the default value of the flag with Viper? I've tried this:

func init() {
    myCmd.Flags().StringVarP(&project, "project", "p", viper.GetString("project"), "Project name")
}

But it seems this is not the way, as I'm getting an empty string if I omit the flag when calling the command. Any ideas? Thanks in advance!

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Radoslav Stoyanov
  • 1,460
  • 5
  • 27
  • 40
  • Can you use the Viper `SetDefault` method? (https://github.com/spf13/viper/blob/8c894384998e656900b125e674b8c20dbf87cc06/viper.go#L1372-L1375) – VonC Feb 16 '21 at 08:46
  • I can, but that's not the case here. I want my flag value to fallback to my config value if flag is omitted and when I call my command with the `--help` flag I want to see my config value in the end of the usage string where it says (default "....") – Radoslav Stoyanov Feb 16 '21 at 16:47

0 Answers0