viper.AutomaticEnv() 获取环境变量无法正常工作。

huangapple go评论104阅读模式
英文:

viper.AutomaticEnv() gets environment variable doesn't work properly

问题

我正在尝试通过设置环境变量来将开发配置文件与生产配置文件隔离。操作系统为MAC OS,我通过在.bash_profile中添加export DEBUG = True来设置一个名为DEBUG的环境变量。echo $debug可以正确获取到值true。我使用viper编写了一个函数来获取"debug"的值。但是打印出来是nil。哪里出错了?

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

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

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)
}

答案1

得分: 2

viper只会查找与您已经告诉它的参数匹配的环境变量。例如,如果您在调用viper.AutomaticEnv()之前使用viper.SetDefault("debug", true),它应该会按照您的期望获取$debug环境变量。

英文:

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.

答案2

得分: 1

如果你使用的是VSCode,你应该在launch.json中添加env。

"configurations": [
    {
        "name": "Launch",
        "type": "go",
        "request": "launch",
        "mode": "auto",
        "program": "${fileDirname}",
        "env": {"DEBUG": "true"},
        "args": []
    }
]
英文:

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": []
    }
]

答案3

得分: 0

我认为这是因为环境变量是区分大小写的。这是来自viper readme的一句引用:

> 在处理环境变量时,重要的是要认识到Viper将环境变量视为区分大小写。

由于你设置了DEBUG并读取了debug,所以这是可以预料的。我不明白为什么bash对于echo $debug返回true,因为bash也应该是区分大小写的。

英文:

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.

huangapple
  • 本文由 发表于 2021年11月5日 22:23:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/69854763.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定