Cookies management by TermsFeed Cookie Consent

πŸƒ Environment variables in Go

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

Thank you for being on our site 😊. If you like our tutorials and examples, please consider supporting us with a cup of coffee and we'll turn it into more great Go examples.

Have a great day!

Buy Me A Coffee

♾️ Infinite loop in Go

Learn how to define a “while true” loop
introduction loop

πŸ“” Convert a struct to io.Reader in Go

Learn how to convert a struct to io.Reader and send it as an HTTP POST request body
introduction http

πŸ“Ÿ Convert HTTP response io.ReadCloser to string in Go

Learn how to convert a HTTP client response body to string
introduction http