100 lines
2.5 KiB
Go
100 lines
2.5 KiB
Go
package config
|
|
|
|
import (
|
|
"fmt"
|
|
"net"
|
|
"os"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
type Config struct {
|
|
HTTPAddr string
|
|
MetricsAddr string
|
|
DatabaseURL string
|
|
LogLevel string
|
|
ReadinessTimeout time.Duration
|
|
ShutdownTimeout time.Duration
|
|
}
|
|
|
|
type LookupEnv func(string) (string, bool)
|
|
|
|
func Load() (Config, error) {
|
|
return LoadFromEnv(os.LookupEnv)
|
|
}
|
|
|
|
func LoadFromEnv(lookup LookupEnv) (Config, error) {
|
|
config := Config{
|
|
HTTPAddr: valueOrDefault(lookup, "HTTP_ADDR", ":8080"),
|
|
MetricsAddr: valueOrDefault(lookup, "METRICS_ADDR", ":9090"),
|
|
DatabaseURL: strings.TrimSpace(valueOrDefault(lookup, "DATABASE_URL", "")),
|
|
LogLevel: strings.ToLower(strings.TrimSpace(valueOrDefault(lookup, "LOG_LEVEL", "info"))),
|
|
ReadinessTimeout: time.Second,
|
|
ShutdownTimeout: 10 * time.Second,
|
|
}
|
|
|
|
if value, ok := lookup("READINESS_TIMEOUT"); ok {
|
|
duration, err := time.ParseDuration(value)
|
|
if err != nil {
|
|
return Config{}, fmt.Errorf("parse READINESS_TIMEOUT: %w", err)
|
|
}
|
|
config.ReadinessTimeout = duration
|
|
}
|
|
if value, ok := lookup("SHUTDOWN_TIMEOUT"); ok {
|
|
duration, err := time.ParseDuration(value)
|
|
if err != nil {
|
|
return Config{}, fmt.Errorf("parse SHUTDOWN_TIMEOUT: %w", err)
|
|
}
|
|
config.ShutdownTimeout = duration
|
|
}
|
|
|
|
if err := config.Validate(); err != nil {
|
|
return Config{}, err
|
|
}
|
|
return config, nil
|
|
}
|
|
|
|
func (config Config) Validate() error {
|
|
if err := validateAddress("HTTP_ADDR", config.HTTPAddr); err != nil {
|
|
return err
|
|
}
|
|
if err := validateAddress("METRICS_ADDR", config.MetricsAddr); err != nil {
|
|
return err
|
|
}
|
|
if config.ReadinessTimeout <= 0 {
|
|
return fmt.Errorf("READINESS_TIMEOUT must be positive")
|
|
}
|
|
if config.ShutdownTimeout <= 0 {
|
|
return fmt.Errorf("SHUTDOWN_TIMEOUT must be positive")
|
|
}
|
|
switch config.LogLevel {
|
|
case "debug", "info", "warn", "error":
|
|
default:
|
|
return fmt.Errorf("LOG_LEVEL must be one of debug, info, warn, or error")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func valueOrDefault(lookup LookupEnv, key, fallback string) string {
|
|
if value, ok := lookup(key); ok {
|
|
return value
|
|
}
|
|
return fallback
|
|
}
|
|
|
|
func validateAddress(name, address string) error {
|
|
if address == "" {
|
|
return fmt.Errorf("%s must not be empty", name)
|
|
}
|
|
_, port, err := net.SplitHostPort(address)
|
|
if err != nil {
|
|
return fmt.Errorf("%s must be a host:port address: %w", name, err)
|
|
}
|
|
number, err := strconv.Atoi(port)
|
|
if err != nil || number < 0 || number > 65535 {
|
|
return fmt.Errorf("%s port must be between 0 and 65535", name)
|
|
}
|
|
return nil
|
|
}
|