Environment variables are often used as a way to store the app configuration values. Instead of keeping sensitive data like passwords in a code repository, we can just set them as environment variables that the program then reads while running. In Golang’s os
package, there are some functions that make it easy to set or unset environment variables, get or list environment variables, and clear environment variables.
func Getenv(key string) string
gets value of thekey
environment variable. If the variable is not set it returns empty string.func LookupEnv(key string) (string, bool)
returns the value of thekey
environment variable and a boolean flag that is true if the variable is set. WithLookupEnv()
, you can test if an environment variable exists.func Setenv(key, value string) error
sets thevalue
of thekey
environment variable. It returns an error if it’s not possible.func Unsetenv(key string) error
unsets thekey
environment variable and returns an error if it’s not possible.func Environ() []string
returns all environment variables askey=value
strings.func Clearenv()
deletes all environment variables.
Look at the example to compare how these functions work:
package main
import (
"fmt"
"log"
"os"
"strings"
)
const userKey = "GOSAMPLES_USER"
func main() {
// set environment variable
err := os.Setenv(userKey, "admin")
if err != nil {
log.Fatal(err)
}
// get environment variable
fmt.Printf("os.Getenv(): %s=%s\n", userKey, os.Getenv(userKey))
// iterate over all environment variables and check if our variable is set
for _, envStr := range os.Environ() {
if strings.HasPrefix(envStr, userKey) {
fmt.Printf("os.Environ(): %s environment variable is set: %s\n", userKey, envStr)
}
}
// lookup environment variable
val, isSet := os.LookupEnv(userKey)
fmt.Printf("os.LookupEnv(): %s variable is set: %t, value: %s\n", userKey, isSet, val)
// unset environment variable
if err := os.Unsetenv(userKey); err != nil {
log.Fatal(err)
}
// lookup environment variable again - now it should not be set
val, isSet = os.LookupEnv(userKey)
fmt.Printf("os.Unsetenv(); %s variable is set: %t, value: %s\n", userKey, isSet, val)
// clear environment variables
os.Clearenv()
fmt.Printf("os.Clearenv(): number of environment variables: %d\n", len(os.Environ()))
}
Output:
os.Getenv(): GOSAMPLES_USER=admin
os.Environ(): GOSAMPLES_USER environment variable is set: GOSAMPLES_USER=admin
os.LookupEnv(): GOSAMPLES_USER variable is set: true, value: admin
os.Unsetenv(); GOSAMPLES_USER variable is set: false, value:
os.Clearenv(): number of environment variables: 0