Files
mtusi2026lab2/internal/platform/config/config.go
T

106 lines
3.0 KiB
Go

// Package config reads the process configuration from the environment.
// Settings have defaults suited to the lab stand, except credentials, which
// are required and read from files named by *_FILE variables so that their
// values never appear in the environment. An invalid value stops the process
// at start-up with a message naming the variable, never the secret.
package config
import (
"fmt"
"log/slog"
"net"
"os"
"strconv"
"strings"
"time"
)
type Config struct {
Host string
Port int
Env string
LogLevel slog.Level
ShutdownTimeout time.Duration
MaxBodyBytes int64
DatabaseURL string
}
// Lookup reads one variable, reporting whether it was set; os.LookupEnv
// in production, a map in tests.
type Lookup func(key string) (string, bool)
func Load(lookup Lookup) (Config, error) {
cfg := Config{
Host: "0.0.0.0",
Port: 8080,
Env: "lab",
LogLevel: slog.LevelInfo,
ShutdownTimeout: 8 * time.Second,
MaxBodyBytes: 64 * 1024,
}
if v, ok := lookup("APP_HOST"); ok {
if strings.TrimSpace(v) == "" {
return Config{}, fmt.Errorf("APP_HOST must not be empty")
}
cfg.Host = v
}
if v, ok := lookup("APP_PORT"); ok {
port, err := strconv.Atoi(v)
if err != nil || port < 1 || port > 65535 {
return Config{}, fmt.Errorf("APP_PORT must be an integer between 1 and 65535, got %q", v)
}
cfg.Port = port
}
if v, ok := lookup("APP_ENV"); ok && strings.TrimSpace(v) != "" {
cfg.Env = v
}
if v, ok := lookup("APP_LOG_LEVEL"); ok {
var level slog.Level
if err := level.UnmarshalText([]byte(v)); err != nil {
return Config{}, fmt.Errorf("APP_LOG_LEVEL must be debug, info, warn or error, got %q", v)
}
cfg.LogLevel = level
}
if v, ok := lookup("APP_SHUTDOWN_TIMEOUT"); ok {
d, err := time.ParseDuration(v)
if err != nil || d <= 0 {
return Config{}, fmt.Errorf("APP_SHUTDOWN_TIMEOUT must be a positive duration such as 8s, got %q", v)
}
cfg.ShutdownTimeout = d
}
if v, ok := lookup("APP_MAX_BODY_BYTES"); ok {
n, err := strconv.ParseInt(v, 10, 64)
if err != nil || n <= 0 {
return Config{}, fmt.Errorf("APP_MAX_BODY_BYTES must be a positive integer, got %q", v)
}
cfg.MaxBodyBytes = n
}
var err error
if cfg.DatabaseURL, err = secret(lookup, "DATABASE_URL_FILE"); err != nil {
return Config{}, err
}
return cfg, nil
}
// secret reads the file named by the variable; surrounding whitespace,
// including the trailing newline editors add, is dropped.
func secret(lookup Lookup, key string) (string, error) {
path, ok := lookup(key)
if !ok || strings.TrimSpace(path) == "" {
return "", fmt.Errorf("%s must name a file with the value", key)
}
raw, err := os.ReadFile(path)
if err != nil {
return "", fmt.Errorf("%s: cannot read %s: %w", key, path, err)
}
value := strings.TrimSpace(string(raw))
if value == "" {
return "", fmt.Errorf("%s: file %s is empty", key, path)
}
return value, nil
}
func (c Config) Addr() string {
return net.JoinHostPort(c.Host, strconv.Itoa(c.Port))
}