// Package config loads and validates the backend's runtime configuration from // the process environment. package config import ( "fmt" "os" ) // Config holds the backend's runtime configuration. type Config struct { // HTTPAddr is the listen address of the HTTP listener (host:port). HTTPAddr string // LogLevel is the zap log level: "debug", "info", "warn" or "error". LogLevel string } // Defaults applied when the corresponding environment variable is unset. const ( defaultHTTPAddr = ":8080" defaultLogLevel = "info" ) // Load reads the configuration from the environment, applies defaults for // unset variables, and validates the result. func Load() (Config, error) { c := Config{ HTTPAddr: envOr("BACKEND_HTTP_ADDR", defaultHTTPAddr), LogLevel: envOr("BACKEND_LOG_LEVEL", defaultLogLevel), } if err := c.validate(); err != nil { return Config{}, err } return c, nil } // validate reports whether the configuration values are acceptable. func (c Config) validate() error { switch c.LogLevel { case "debug", "info", "warn", "error": default: return fmt.Errorf("config: invalid BACKEND_LOG_LEVEL %q", c.LogLevel) } if c.HTTPAddr == "" { return fmt.Errorf("config: BACKEND_HTTP_ADDR must not be empty") } return nil } // envOr returns the value of the environment variable named key, or fallback // when the variable is unset or empty. func envOr(key, fallback string) string { if v := os.Getenv(key); v != "" { return v } return fallback }