Go by Example

Environment Variables

os.Getenv reads env vars; os.LookupEnv distinguishes "not set" from "set to empty string" - critical for required config validation at startup.

Environment variables pass configuration from the operating system to a process. Getenv returns an empty string when a variable is absent; LookupEnv also reports whether it was set.

Use LookupEnv when an empty value differs from a missing value. This example reads a non-secret setting without printing its value.

package main
 
import (
    "fmt"
    "os"
)
 
func main() {
    mode, ok := os.LookupEnv("APP_MODE")
    if !ok {
        fmt.Println("APP_MODE is not set")
        return
    }
    fmt.Println("APP_MODE is set:", mode)
}

In production

Read and validate required configuration at startup, then report missing names without logging secret values. Changes from Setenv affect future child processes that inherit the environment. Because environment variables are process-wide state, avoid changing them after startup.

Enjoyed this? Get more software craft delivered to your inbox.