Environment Variables Config Precedence

Load config from environment variables with defaults and validation in Go.

GoConfig Management

Code

snippet
package main
import ("os";"strconv";"fmt")
type Config struct {
    Port int
    Host string
    Debug bool
}
func LoadConfig() Config {
    port, _ := strconv.Atoi(getEnv("PORT", "8080"))
    return Config{
        Port: port,
        Host: getEnv("HOST", "localhost"),
        Debug: getEnv("DEBUG", "false") == "true",
    }
}
func getEnv(key, def string) string {
    if v := os.Getenv(key); v != "" { return v }
    return def
}