Go by Example: Environment Variables
Go 1.23
Learn how to interact with Environment Variables in Go. This example demonstrates setting, retrieving, and listing environment variables using the `os` package, a crucial skill for configuring applications across different environments.
Code
package main
import (
"fmt"
"os"
"strings"
)
func main() {
// Setting an environment variable
os.Setenv("FOO", "1")
fmt.Println("FOO:", os.Getenv("FOO"))
fmt.Println("BAR:", os.Getenv("BAR"))
// Listing all environment variables
fmt.Println()
for _, e := range os.Environ() {
pair := strings.SplitN(e, "=", 2)
// Print only the key
// fmt.Println(pair[0])
// Just printing first few for brevity in example
if strings.HasPrefix(pair[0], "FOO") {
fmt.Println(pair[0], "=", pair[1])
}
}
}Explanation
Environment variables are the standard way to configure applications across different environments (dev, stage, prod), following the 12-Factor App methodology.
Best practices for handling env vars:
- Use
os.LookupEnv: Unlikeos.Getenv, which returns "" for both missing and empty variables,LookupEnvreturns a boolean(value, exists), allowing you to detect missing configuration explicitly. - Configuration Structs: Don't scatter
os.Getenvcalls throughout your code. Load them once into a config struct at startup (often using tools like Viper orkelseyhightower/envconfig). - Secrets: Never hardcode secrets. Always inject them via environment variables or a secret manager.
Code Breakdown
11
os.Setenv sets a key-value pair for the current process. This change is temporary and only affects the running program and its children.
12
os.Getenv retrieves the value of the "FOO" environment variable. If "FOO" wasn't set, it would return an empty string "".
17
os.Environ returns a slice of strings representing the environment in the form "KEY=value". This allows you to iterate over all set variables.
18
We split each environment string on the first "=" character to separate the key from the value. The '2' argument limits the split to 2 substrings.
22
Filtering the output to show only variables starting with "FOO" to keep the example output clean.

