How to Read Environment Variables in Go

Use the `os.Getenv` function from the standard library to retrieve a specific environment variable, or `os.Environ` to get a slice of all variables as "KEY=VALUE" strings.

Use the os.Getenv function from the standard library to retrieve a specific environment variable, or os.Environ to get a slice of all variables as "KEY=VALUE" strings. Always handle missing variables gracefully by checking the returned string or using os.LookupEnv to distinguish between an unset variable and one explicitly set to an empty string.

Here is a practical example showing how to safely read a configuration value with a fallback default:

package main

import (
	"fmt"
	"os"
)

func main() {
	// Method 1: Get a single variable with a default fallback
	port := os.Getenv("PORT")
	if port == "" {
		port = "8080"
	}

	// Method 2: Use LookupEnv to explicitly check if the key exists
	// This distinguishes between "unset" and "set to empty string"
	if val, ok := os.LookupEnv("DEBUG"); ok {
		fmt.Printf("Debug mode is explicitly set to: %q\n", val)
	} else {
		fmt.Println("DEBUG variable is not set")
	}

	fmt.Printf("Server starting on port %s\n", port)
}

To run this code with a custom environment variable, use the shell syntax appropriate for your OS. On Linux or macOS, prefix the command with the variable assignment:

PORT=3000 DEBUG=true go run main.go

On Windows (PowerShell), use the $env: prefix:

$env:PORT="3000"; $env:DEBUG="true"; go run main.go

For production applications, it is common to validate these values immediately after reading them. If you need to parse the value into a specific type (like an integer), use the strconv package and handle the error:

import "strconv"

portStr := os.Getenv("PORT")
port, err := strconv.Atoi(portStr)
if err != nil {
    // Handle error: log and exit, or use a default
    fmt.Println("Invalid PORT format, defaulting to 8080")
    port = 8080
}

Remember that environment variables are strings; you must always parse them if you need numeric or boolean types. Also, be aware that os.Getenv returns an empty string if the key is missing, which can lead to silent failures if you don't check for it or provide a default. Using os.LookupEnv is generally safer for critical configuration flags where the distinction between "missing" and "empty" matters.