Skip to main content
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.

Working with Environment Variables

Go’s os package provides functions to set, get, and list environment variables:
package main

import (
	"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])
	}
}

Running the Program

Basic Execution

Running the program shows that we pick up the value for FOO that we set in the program, but BAR returns empty:
go run environment-variables.go
The list of environment variables will depend on your particular machine and shell configuration.

Setting Variables at Runtime

You can set environment variables before running the program:
BAR=2 go run environment-variables.go

Core Functions

os.Setenv

Sets an environment variable for the current process:
os.Setenv("KEY", "value")

os.Getenv

Retrieves an environment variable. Returns empty string if not found:
value := os.Getenv("KEY")

os.Environ

Returns all environment variables as a slice of KEY=value strings:
envs := os.Environ()

Checking for Missing Variables

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.

Parsing Environment Variables

To parse all environment variables into a map:
envMap := make(map[string]string)
for _, env := range os.Environ() {
    pair := strings.SplitN(env, "=", 2)
    if len(pair) == 2 {
        envMap[pair[0]] = pair[1]
    }
}
os.Setenv() only affects the current process and its child processes. It does not modify the parent shell’s environment.

Common Use Cases

Environment variables are ideal for configuration that changes between deployments:
dbHost := os.Getenv("DB_HOST")
dbPort := os.Getenv("DB_PORT")
apiKey := os.Getenv("API_KEY")
Use environment variables to differentiate between environments:
env := os.Getenv("ENVIRONMENT")
if env == "production" {
    // Production configuration
} else {
    // Development configuration
}
Store sensitive information like API keys and passwords in environment variables rather than hardcoding them:
apiSecret := os.Getenv("API_SECRET")
if apiSecret == "" {
    log.Fatal("API_SECRET environment variable is required")
}

Best Practices

Provide Defaults

Always provide sensible defaults for non-critical configuration:
port := os.Getenv("PORT")
if port == "" {
    port = "8080"
}

Validate Required Vars

Exit early if required environment variables are missing:
apiKey := os.Getenv("API_KEY")
if apiKey == "" {
    log.Fatal("API_KEY required")
}

Command Line Arguments

Learn about passing parameters via command-line arguments

Command Line Flags

Explore structured option parsing with flags

Build docs developers (and LLMs) love