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()
}
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
