Get variables from the environment in go?

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

Get variables from the environment in go?

问题

我有一个数据集存储在环境变量GOPATH中,我想在我的程序中以编程方式提取这些数据。我希望将所有的环境变量作为map[string]interface{}获取。这是因为我想将环境变量的值与我当前获取的JSON配置文件集成在一起。

var data map[string]interface{}

file, err := ioutil.ReadFile(configFilePath)
if err != nil {
  log.Fatal(err)
}
err = json.Unmarshal(file, &data)
if err != nil {
  log.Fatal(err)
}
英文:

I have data set in the environment variable GOPATH and I would like to programatically extract this data in my program. I would prefer to fetch all the ENV variables as a map[string]interface{}. This is because I want to integrate the ENV values with my JSON config witch I currently fetch like so.

 var data map[string]interface{}

 file, err := ioutil.ReadFile(configFilePath)
 if err != nil {
   log.Fatal(err)
 }
 err = json.Unmarshal(file, &data)
 if err != nil {
   log.Fatal(err)
 }

答案1

得分: 9

os.Environ() 返回表示环境的字符串,格式为 "key=value"。要创建一个映射,可以遍历这些字符串,以 "=" 进行分割,并设置映射的条目。

m := make(map[string]string)
for _, e := range os.Environ() {
    if i := strings.Index(e, "="); i >= 0 {
        m[e[:i]] = e[i+1:]
    }
}
英文:

os.Environ() returns the strings representing the environment in the form "key=value". To create a map, iterate through the strings, split on "=" and set the map entry.

m := make(map[string]string)
for _, e := range os.Environ() {
    if i := strings.Index(e, "="); i >= 0 {
        m[e[:i]] = e[i+1:]
    }
}

huangapple
  • 本文由 发表于 2015年3月27日 13:33:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/29293961.html
匿名

发表评论

匿名网友

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

确定