Environment variables

suggest change

Environment variables provide external configuration to applications without modifying source code or rebuilding binaries. Following the Twelve-Factor App methodology, configuration that varies across deployment environments (such as database connection strings, API secrets, server ports, and feature toggles) should be stored in environment variables.

In Go, the standard library os and strconv packages provide built-in functions to read, write, check, and iterate over environment variables.


1. Reading Environment Variables

Simple Retrieval with os.Getenv

os.Getenv returns the value of the environment variable as a string. If the variable is not set, it returns an empty string "":

package main

import (
	"fmt"
	"os"
)

func main() {
	port := os.Getenv("PORT")
	if port == "" {
		port = "8080" // Default fallback
	}

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

Distinguishing Unset from Empty with os.LookupEnv

os.Getenv cannot distinguish between a variable that was never set and one explicitly assigned to an empty string (e.g. export CACHE_PREFIX=""). Use os.LookupEnv, which returns a boolean ok indicating presence:

package main

import (
	"fmt"
	"os"
)

func getEnvOrDefault(key, fallback string) string {
	if value, exists := os.LookupEnv(key); exists {
		return value
	}
	return fallback
}

func main() {
	dbHost := getEnvOrDefault("DB_HOST", "localhost")
	fmt.Printf("Connecting to DB host: %s\n", dbHost)
}

2. Setting and Clearing Variables

You can set or remove environment variables within the current process and any child processes it spawns:

package main

import (
	"fmt"
	"os"
)

func main() {
	// Set an environment variable
	err := os.Setenv("APP_ENV", "production")
	if err != nil {
		fmt.Printf("Failed to set env: %v\n", err)
	}

	fmt.Println("APP_ENV:", os.Getenv("APP_ENV")) // Output: production

	// Remove an environment variable
	_ = os.Unsetenv("APP_ENV")
	fmt.Println("After unset:", os.Getenv("APP_ENV")) // Output: ""
}

Note: os.Setenv only affects the current Go process and any child processes executed via os/exec. It does not modify the parent shell or system-wide environment variables.


3. Listing All Environment Variables with os.Environ

os.Environ returns a copy of strings representing the environment in the form "key=value":

package main

import (
	"fmt"
	"os"
	"strings"
)

func main() {
	for _, env := range os.Environ() {
		pair := strings.SplitN(env, "=", 2)
		key := pair[0]
		value := pair[1]

		// Print only application-specific variables
		if strings.HasPrefix(key, "APP_") {
			fmt.Printf("%s -> %s\n", key, value)
		}
	}
}

4. Parsing Typed Configuration

Environment variables are always strings. Real-world applications typically require typed integers, booleans, durations, or string lists:

package main

import (
	"fmt"
	"os"
	"strconv"
	"strings"
	"time"
)

type Config struct {
	Port         int
	Debug        bool
	ReadTimeout  time.Duration
	AllowedHosts []string
}

func LoadConfig() (*Config, error) {
	cfg := &Config{
		Port:         8080,
		Debug:        false,
		ReadTimeout:  5 * time.Second,
		AllowedHosts: []string{"localhost"},
	}

	if portStr := os.Getenv("APP_PORT"); portStr != "" {
		port, err := strconv.Atoi(portStr)
		if err != nil {
			return nil, fmt.Errorf("invalid APP_PORT: %w", err)
		}
		cfg.Port = port
	}

	if debugStr := os.Getenv("APP_DEBUG"); debugStr != "" {
		debug, err := strconv.ParseBool(debugStr)
		if err != nil {
			return nil, fmt.Errorf("invalid APP_DEBUG: %w", err)
		}
		cfg.Debug = debug
	}

	if timeoutStr := os.Getenv("APP_READ_TIMEOUT"); timeoutStr != "" {
		timeout, err := time.ParseDuration(timeoutStr)
		if err != nil {
			return nil, fmt.Errorf("invalid APP_READ_TIMEOUT: %w", err)
		}
		cfg.ReadTimeout = timeout
	}

	if hostsStr := os.Getenv("APP_ALLOWED_HOSTS"); hostsStr != "" {
		cfg.AllowedHosts = strings.Split(hostsStr, ",")
	}

	return cfg, nil
}

func main() {
	cfg, err := LoadConfig()
	if err != nil {
		fmt.Printf("Configuration error: %v\n", err)
		os.Exit(1)
	}

	fmt.Printf("Loaded Config: %+v\n", cfg)
}

5. Loading .env Files During Local Development

During local development, developers frequently store environment variables in a .env file instead of setting them manually in the shell. While production deployments should inject real environment variables (e.g. Kubernetes Secrets, AWS ECS, Docker env files), packages like github.com/joho/godotenv allow automatic loading in development:

package main

import (
	"log"
	"os"

	"github.com/joho/godotenv"
)

func main() {
	// Only load .env file if it exists (e.g., local development)
	if err := godotenv.Load(); err != nil {
		log.Println("No .env file found; using system environment variables")
	}

	apiKey := os.Getenv("STRIPE_API_KEY")
	if apiKey == "" {
		log.Fatal("STRIPE_API_KEY environment variable is required")
	}
}

Best Practices

  1. Fail Fast on Missing Required Variables: Verify that all mandatory configuration parameters (e.g., database URLs, cryptographic keys) are present during application startup in main(), failing with a clear error message.
  2. Never Commit .env Files with Production Secrets: Add .env, .env.local, and *.secret to your .gitignore to prevent leaking production credentials into source control.
  3. Use Namespace Prefixes: Prefix related environment variables with your application name (e.g., MYAPP_DB_HOST, MYAPP_PORT) to prevent name collisions with other tools and system variables.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents