Learn how to set, get, and list environment variables in Go programs using the os package
Environment variables are a universal mechanism for conveying configuration information to Unix programs. They’re an essential part of the twelve-factor app methodology for building modern, cloud-native applications.
Go’s os package provides functions to set, get, and list environment variables:
package mainimport ( "fmt" "os" "strings")func main() { // To set a key/value pair, use `os.Setenv`. To get a // value for a key, use `os.Getenv`. This will return // an empty string if the key isn't present in the // environment. os.Setenv("FOO", "1") fmt.Println("FOO:", os.Getenv("FOO")) fmt.Println("BAR:", os.Getenv("BAR")) // Use `os.Environ` to list all key/value pairs in the // environment. This returns a slice of strings in the // form `KEY=value`. You can `strings.SplitN` them to // get the key and value. Here we print all the keys. fmt.Println() for _, e := range os.Environ() { pair := strings.SplitN(e, "=", 2) fmt.Println(pair[0]) }}
Since os.Getenv() returns an empty string for missing variables, you might want to distinguish between an empty value and a missing variable:
value, exists := os.LookupEnv("KEY")if !exists { fmt.Println("KEY is not set")} else if value == "" { fmt.Println("KEY is set but empty")} else { fmt.Println("KEY =", value)}
Use os.LookupEnv() instead of os.Getenv() when you need to distinguish between unset variables and variables set to empty strings.