Load Environment Variables Into Config
Read configuration from environment variables with typed parsing and defaults, validating required fields at startup rather than at first use.
Code
package config
import (
"fmt"
"os"
"strconv"
)
type Config struct {
Port int
DatabaseURL string
Debug bool
}
func Load() (Config, error) {
databaseURL := os.Getenv("DATABASE_URL")
if databaseURL == "" {
return Config{}, fmt.Errorf("DATABASE_URL is required")
}
port, err := strconv.Atoi(getEnv("PORT", "8080"))
if err != nil {
return Config{}, fmt.Errorf("PORT must be a number: %w", err)
}
return Config{
Port: port,
DatabaseURL: databaseURL,
Debug: getEnv("DEBUG", "false") == "true",
}, nil
}
func getEnv(key, fallback string) string {
if value, ok := os.LookupEnv(key); ok {
return value
}
return fallback
}Report a problem with this exampleOpens a pre-filled issue on GitHub.