How to Implement 12-Factor App Configuration in Go

Configure Go apps for 12-Factor compliance by reading settings from environment variables using os.Getenv and os.LookupEnv.

Implement 12-Factor App configuration in Go by reading settings from environment variables, using os.Getenv for retrieval and os.LookupEnv for defaults, and validating them at startup.

package main

import (
	"fmt"
	"log"
	"os"
)

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

	dbURL, ok := os.LookupEnv("DATABASE_URL")
	if !ok {
		log.Fatal("DATABASE_URL is required")
	}

	fmt.Printf("Starting server on port %s with DB: %s\n", port, dbURL)
}
  1. Set environment variables in your deployment shell or container orchestration file.
  2. Use os.Getenv to read optional values and provide fallbacks.
  3. Use os.LookupEnv to read required values and fail fast if missing.
  4. Validate all configuration values immediately after loading them.
  5. Never hardcode secrets or paths in your source code.