Golang / GoLang Production Patterns and Web Standards Interview Questions
What are the idiomatic Go patterns for managing application configuration?
Go applications typically load configuration from environment variables (twelve-factor app pattern), config files, or a combination. The idiomatic approach is to load all configuration at startup, validate it, and inject it into components as a struct β not read environment variables throughout the codebase.
// Config struct Γ’ΒΒ single source of truth type Config struct { HTTP struct { Port int `env:"HTTP_PORT" default:"8080"` ReadTimeout time.Duration `env:"HTTP_READ_TIMEOUT" default:"5s"` WriteTimeout time.Duration `env:"HTTP_WRITE_TIMEOUT" default:"10s"` } Database struct { URL string `env:"DATABASE_URL" required:"true"` MaxConnections int `env:"DB_MAX_CONNECTIONS" default:"25"` } Auth struct { JWTSecret string `env:"JWT_SECRET" required:"true"` TokenTTL time.Duration `env:"TOKEN_TTL" default:"24h"` } } // Load from environment Γ’ΒΒ validate at startup func loadConfig() (*Config, error) { var cfg Config // Use envconfig, viper, or manual os.Getenv cfg.HTTP.Port = mustEnvInt("HTTP_PORT", 8080) cfg.Database.URL = mustEnv("DATABASE_URL") cfg.Auth.JWTSecret = mustEnv("JWT_SECRET") if cfg.Auth.JWTSecret == "" { return nil, errors.New("JWT_SECRET must not be empty") } return &cfg, nil } func mustEnv(key string) string { v := os.Getenv(key) if v == "" { log.Fatalf("required environment variable %s is not set", key) } return v } func main() { cfg, err := loadConfig() if err != nil { log.Fatalf("invalid configuration: %v", err) } // Inject cfg into all components db := openDB(cfg.Database.URL, cfg.Database.MaxConnections) srv := newServer(cfg.HTTP, db) srv.Start() }
More Related questions...