如何读取Linux环境变量,在Go中



我正在尝试读取env变量,例如将密码存储在代码之外。尝试在.bashrc/etc/environment中设置它,但没有成功:

func Test_env(t *testing.T) {
variable, exists := os.LookupEnv("SOME_PASS_ENV")
log.Printf("%v%v", variable, exists)
}
=== RUN   Test_env
2020/11/06 12:26:07 env_value:  exists?: false

/etc/environment中设置变量后,该变量在全局范围内可用。我还能做什么?谢谢

以防万一,getEnv("SOME_PASS_ENV")什么都不返回,这就是为什么使用LookupEnv进行检查的原因。

使用os。当您不需要区分空的环境变量值和未设置的环境变量时,Getenv可以获取环境变量的值。

func Getenv(key string) string
Getenv retrieves the value of the environment variable named by the key. It
returns the value, which will be empty if the variable is not present. To
distinguish between an empty value and an unset value, use LookupEnv.

使用os。当您确实需要区分空的环境变量值和未设置的环境变量时,Lookupenv。

func LookupEnv(key string) (string, bool)
LookupEnv retrieves the value of the environment variable named by the key.
If the variable is present in the environment the value (which may be empty)
is returned and the boolean is true. Otherwise the returned value will be
empty and the boolean will be false.

使用os。Environ以获取所有环境变量及其值的列表。

func Environ() []string
Environ returns a copy of strings representing the environment, in the form
"key=value".

旁注:也许您没有正确设置环境变量。在运行go test之前,请尝试直接在shell中设置export SOME_PASS_ENV=some_value

最新更新