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
}
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
package api
import (
"net/http"
"runtime/debug"
)
Expose build metadata for debugging deploys
export interface RetryOptions {
retries: number;
baseMs: number;
maxMs: number;
signal?: AbortSignal;
onRetry?: (attempt: number, delay: number, err: unknown) => void;
Exponential backoff with jitter for retries
package dbutil
import (
"context"
"github.com/jackc/pgconn"
Retry Postgres serialization failures with bounded attempts
package files
import (
"context"
"time"
Presigned S3 upload URLs (AWS SDK v2)
package deps
import (
"net"
"net/http"
"time"
HTTP client tuned for production: timeouts, transport, and connection reuse
package api
import (
"io"
"net/http"
"os"
Safe multipart uploads using temp files (bounded memory)
Share this code
Here's the card — post it anywhere.