Files
mtusi2026lab2/app/internal/config/config.go
T
2026-10-23 18:55:20 +03:00

108 lines
2.5 KiB
Go

// AGENT: All runtime configuration is read here so every other package receives
// explicit values instead of calling os.Getenv. Values are compatible with
// .env.example and support the *_FILE convention used by Compose secrets.
package config
import (
"fmt"
"os"
"strconv"
"strings"
"time"
)
type Config struct {
Host string
Port string
SessionTTL time.Duration
DatabaseURL string
CacheURL string
DBMaxConns int32
DBTimeout time.Duration
RedisTimeout time.Duration
StartupWait time.Duration
}
func Load() (Config, error) {
cfg := Config{
Host: envOr("APP_HOST", "0.0.0.0"),
Port: envOr("APP_PORT", "8080"),
DBMaxConns: 10,
DBTimeout: 5 * time.Second,
RedisTimeout: 2 * time.Second,
StartupWait: 30 * time.Second,
}
ttlSeconds, err := strconv.Atoi(envOr("SESSION_TTL_SECONDS", "3600"))
if err != nil || ttlSeconds < 1 {
return cfg, fmt.Errorf("SESSION_TTL_SECONDS must be a positive integer")
}
cfg.SessionTTL = time.Duration(ttlSeconds) * time.Second
if value := envOr("DB_POOL_MAX_CONNS", ""); value != "" {
n, convErr := strconv.Atoi(value)
if convErr != nil || n < 1 || n > 100 {
return cfg, fmt.Errorf("DB_POOL_MAX_CONNS must be an integer between 1 and 100")
}
cfg.DBMaxConns = int32(n)
}
cfg.DatabaseURL, err = secret("DATABASE_URL")
if err != nil {
return cfg, err
}
if cfg.DatabaseURL == "" {
return cfg, fmt.Errorf("DATABASE_URL or DATABASE_URL_FILE is required")
}
cfg.CacheURL, err = secret("CACHE_URL")
if err != nil {
return cfg, err
}
if cfg.CacheURL == "" {
cfg.CacheURL, err = secret("REDIS_URL")
if err != nil {
return cfg, err
}
}
if cfg.CacheURL == "" {
return cfg, fmt.Errorf("CACHE_URL or CACHE_URL_FILE is required")
}
if value := strings.ToLower(envOr("SESSION_STORE", "redis")); value != "redis" {
return cfg, fmt.Errorf("SESSION_STORE must be redis (got %q)", value)
}
return cfg, nil
}
func envOr(name, fallback string) string {
if value := os.Getenv(name); value != "" {
return value
}
return fallback
}
func secret(name string) (string, error) {
if value := os.Getenv(name); value != "" {
return value, nil
}
path := os.Getenv(name + "_FILE")
if path == "" {
return "", nil
}
data, err := os.ReadFile(path)
if err != nil {
return "", fmt.Errorf("read %s_FILE: %w", name, err)
}
value := strings.TrimSpace(string(data))
if value == "" {
return "", fmt.Errorf("%s_FILE is empty", name)
}
return value, nil
}