Using environment variables in Go

Parsing environment variables with Go is simple, thanks to the standard library os package.

os.Getenv() gets an environment variable. It’s not possible to determine not set or empty. Use os.LookupEnv() to be able to do that.

name := os.Getenv("NAME")

os.Setenv() sets an environment variable.

os.Setenv("NAME", "Flavio")

os.Unsetenv() unsets an environment variable.


os.Clearenv() unsets all environment variables.


os.Environ() returns a slice of strings containing all the environment variables in key=value format.

vars := os.Environ()

os.ExpandEnv() given a string, expands $VAR environment variables entries to the corresponding value.

s := os.ExpandEnv("$NAME is italian")

os.LookupEnv() returns the value of the environment variable in its first parameter if set, otherwise the second parameter is false. Allows to distinguish unset from empty value.

name, ok := os.LookupEnv("NAME")

Download my free Go Handbook!

Download my free Programming Ebooks!