英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论