Environment Variables Config Precedence
Load config from environment variables with defaults and validation in Go.
Code
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
}Report a problem with this exampleOpens a pre-filled issue on GitHub.