go 31 lines · 1 tab

Robust environment parsing for bool/int with explicit defaults

Leah Thompson Jan 2026
1 tab
package config

import (
  "fmt"
  "os"
  "strconv"
)

func Bool(key string, def bool) (bool, error) {
  v := os.Getenv(key)
  if v == "" {
    return def, nil
  }
  b, err := strconv.ParseBool(v)
  if err != nil {
    return false, fmt.Errorf("%s: %w", key, err)
  }
  return b, nil
}

func Int(key string, def int) (int, error) {
  v := os.Getenv(key)
  if v == "" {
    return def, nil
  }
  n, err := strconv.Atoi(v)
  if err != nil {
    return 0, fmt.Errorf("%s: %w", key, err)
  }
  return n, nil
}
1 file · go Explain with highlit

I like config that fails loudly when it’s wrong. The helpers below parse environment variables with explicit defaults and good error messages, which prevents subtle “zero value” behavior in production. This is especially important for flags like ENABLE_BILLING=true and for numeric settings like connection pool sizes, where 0 might mean “unlimited” in a downstream library. I also keep parsing centralized in one package so services don’t reinvent it. The pragmatic approach is: parse once at startup, validate invariants, and then keep config immutable. In production, this makes rollouts safer because bad configs fail fast rather than half-working. It’s unglamorous code, but it eliminates a whole category of outages caused by environment drift between staging and prod.


Related snips

Share this code

Here's the card — post it anywhere.

Robust environment parsing for bool/int with explicit defaults — share card
Link copied