Files
mtusi2026lab2/internal/config/config.go
T

129 lines
2.4 KiB
Go

package config
import (
"fmt"
"log"
"log/slog"
"os"
"strconv"
"strings"
"time"
)
type Config struct {
Server ServerConfig
Logging LoggingConfig
Database DatabaseConfig
}
type ServerConfig struct {
Host string
Port string
MaxInflightRequests int
SessionTTL time.Duration
}
type LoggingConfig struct {
Level slog.Level
}
type DatabaseConfig struct {
URLFile string
}
func (c DatabaseConfig) URL() (string, error) {
return readSecretFile(c.URLFile)
}
func Load() Config {
return Config{
Server: ServerConfig{
Host: getEnv("APP_HOST", "0.0.0.0"),
Port: getEnv("APP_PORT", "8080"),
MaxInflightRequests: getEnvNonNegativeInt("MAX_INFLIGHT_REQUESTS", 0),
SessionTTL: time.Duration(getEnvPositiveInt("SESSION_TTL_SECONDS", 3600)) * time.Second,
},
Logging: LoggingConfig{
Level: getEnvLogLevel("LOG_LEVEL", slog.LevelInfo),
},
Database: DatabaseConfig{
URLFile: getEnv("DATABASE_URL_FILE", "/run/secrets/database_url"),
},
}
}
func getEnv(key, def string) string {
value := os.Getenv(key)
if value == "" {
return def
}
return value
}
func getEnvNonNegativeInt(key string, def int) int {
v := os.Getenv(key)
if v == "" {
return def
}
value, err := strconv.Atoi(v)
if err != nil || value < 0 {
log.Printf("invalid non-negative int for %s=%q, using default %d", key, v, def)
return def
}
return value
}
func getEnvPositiveInt(key string, def int) int {
v := os.Getenv(key)
if v == "" {
return def
}
value, err := strconv.Atoi(v)
if err != nil || value <= 0 {
log.Printf("invalid positive int for %s=%q, using default %d", key, v, def)
return def
}
return value
}
func getEnvLogLevel(key string, def slog.Level) slog.Level {
v := os.Getenv(key)
switch v {
case "DEBUG":
return slog.LevelDebug
case "INFO":
return slog.LevelInfo
case "WARN":
return slog.LevelWarn
case "ERROR":
return slog.LevelError
case "":
return def
default:
log.Printf("invalid log level for %s=%q, using default %s", key, v, def)
return def
}
}
func readSecretFile(path string) (string, error) {
b, err := os.ReadFile(path)
if err != nil {
return "", fmt.Errorf("read secret file %s: %w", path, err)
}
value := strings.TrimSpace(string(b))
if value == "" {
return "", fmt.Errorf("secret file %s is empty", path)
}
return value, nil
}