1

I was trying to isolate the development config file from production config by setting a environment variable. Operating System: MAC OS, I set a environment variable DEBUG = true through .bash_profile by adding export DEBUG = True. echo $debug gets correct value true. I wrote a function using viper which fetches the value of "debug". But print nil. Where part is wrong?

func GetEnvInfo(env string) string {
    viper.AutomaticEnv()
    v := viper.Get(env)
    return v
}

func main() {
    env := GetEnvInfo("debug")
    fmt.Println(env)
}

W.W.G
  • 93
  • 2
  • 6

3 Answers3

2

viper only looks for environment variables matching parameters that you've already told it about. For example, if you say viper.SetDefault("debug", true) before you call viper.AutomaticEnv(), it should then pick up the $debug environment variable as you expect.

1

if you use vscode, you should add env in launch.json.

"configurations": [
    {
        "name": "Launch",
        "type": "go",
        "request": "launch",
        "mode": "auto",
        "program": "${fileDirname}",
        "env": {"DEBUG": "true"},
        "args": []
    }
]
rubbish
  • 11
  • 2
0

I think this is because environment variables are case-sensitive. This is a quote form the viper readme:

When working with ENV variables, it’s important to recognize that Viper treats ENV variables as case sensitive.

Since you set DEBUG and read debug this is expected. I don't understand why bash does returns true for echo $debug since bash is also supposed to be case-sensitive.

Dylan Reimerink
  • 5,874
  • 2
  • 15
  • 21