Last Updated: February 25, 2016
·
12.92K
· snaveen

Get environment variables as a map in golang

Here is a code to get the environment variables as a map in go instead of slice.

 package main

import (
    "fmt"
    "os"
    "strings"
)

func main() {
    getenvironment := func(data []string, getkeyval func(item string) (key, val string)) map[string]string {
        items := make(map[string]string)
        for _, item := range data {
            key, val := getkeyval(item)
            items[key] = val
        }
        return items
    }
    environment := getenvironment(os.Environ(), func(item string) (key, val string) {
        splits := strings.Split(item, "=")
        key = splits[0]
        val = splits[1]
        return
    })
    fmt.Println(environment["KEY"])
}

I needed this because I was looking for a specific environment variable.

4 Responses
Add your response

Thanks for this, it was helpful. There's a subtle bug here which is that values that contain an = sign are not properly handled. You need to change the getkeyval function to:

splits := strings.Split(item, "=")
key = splits[0]
val = strings.Join(splits[1:], "=")
return

Without this fix an environment variable created with export VALUE=some=value will end up as some in the resulting map.

over 1 year ago ·

I needed this because I was looking for a specific environment variable.

To get the value of an environment variable, you can use os.Getenv:

val := os.Getenv("key")
over 1 year ago ·

@jkakar No, you should use strings.SplitN instead of Split. http://play.golang.org/p/myVS4NUwau

over 1 year ago ·

@jkakar No, you should use strings.SplitN instead of Split. http://play.golang.org/p/myVS4NUwau

over 1 year ago ·