package config
import (
"errors"
"os"
"strconv"
"time"
)
type Config struct {
Port int
DatabaseURL string
HTTPTimeout time.Duration
}
func Load() (Config, error) {
port := 8080
if v := os.Getenv("PORT"); v != "" {
p, err := strconv.Atoi(v)
if err != nil {
return Config{}, err
}
port = p
}
db := os.Getenv("DATABASE_URL")
if db == "" {
return Config{}, errors.New("DATABASE_URL is required")
}
timeout := 2 * time.Second
if v := os.Getenv("HTTP_TIMEOUT"); v != "" {
d, err := time.ParseDuration(v)
if err != nil {
return Config{}, err
}
timeout = d
}
return Config{Port: port, DatabaseURL: db, HTTPTimeout: timeout}, nil
}
Config bugs are some of the most expensive production incidents because they vary by environment and can be hard to reproduce. I keep configuration in a typed struct, load it from environment variables, and validate it before the server starts. The validation step is the important part: fail fast with a clear message rather than booting with 0 values that cause weird behavior later. I also parse durations with time.ParseDuration so settings like HTTP_TIMEOUT=2s remain readable. When secrets are involved, I avoid printing them in logs and only log which required keys are missing. This snippet shows a pragmatic “no dependencies” approach, but the discipline scales to envconfig or a full config system later. Good config hygiene makes deploys boring.
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.