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)
}
- Set environment variables in your deployment shell or container orchestration file.
- Use
os.Getenvto read optional values and provide fallbacks. - Use
os.LookupEnvto read required values and fail fast if missing. - Validate all configuration values immediately after loading them.
- Never hardcode secrets or paths in your source code.