🍃 Get, set, list and other operations on environment variables in Golang

April 21, 2021
introduction environment variables

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.

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

✒️ Write to a CSV file in Go

Learn how to write data to a CSV or TSV file
introduction file

🙌 Case-insensitive string comparison in Go

Learn how to compare strings in a case-insensitive manner
introduction strings

🏁 Check if a string starts with a substring in Go

Learn how to use strings.HasPrefix() function
introduction strings