登录
首页 >  Golang >  Go问答

Go 语言中获取 Linux 系统环境变量的方法

来源:stackoverflow

时间:2024-03-04 12:54:28 189浏览 收藏

哈喽!大家好,很高兴又见面了,我是golang学习网的一名作者,今天由我给大家带来一篇《Go 语言中获取 Linux 系统环境变量的方法》,本文主要会讲到等等知识点,希望大家一起学习进步,也欢迎大家关注、点赞、收藏、转发! 下面就一起来看看吧!

问题内容

我正在尝试读取环境变量,例如在我的代码之外存储密码。尝试在 .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 进行设置

今天关于《Go 语言中获取 Linux 系统环境变量的方法》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>