Pablo Jomer
Pablo Jomer

Reputation: 10378

Get variables from the environment in go?

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

Upvotes: 7

Views: 3945

Answers (1)

Thundercat
Thundercat

Reputation: 120951

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

Upvotes: 13

Related Questions