Files
shop10/internal/config/config.go
T

62 lines
1.3 KiB
Go

package config
import (
"fmt"
"os"
"strconv"
"time"
)
type Config struct {
HTTPAddr string
DatabaseURL string
ReadTimeout time.Duration
WriteTimeout time.Duration
SessionTTL time.Duration
CookieSecure bool
}
func Load() (Config, error) {
port := env("APP_PORT", "8080")
cfg := Config{
HTTPAddr: ":" + port,
DatabaseURL: os.Getenv("DATABASE_URL"),
ReadTimeout: durationEnv("HTTP_READ_TIMEOUT", 10*time.Second),
WriteTimeout: durationEnv("HTTP_WRITE_TIMEOUT", 30*time.Second),
SessionTTL: sessionTTL(),
CookieSecure: env("COOKIE_SECURE", "false") == "true",
}
if cfg.DatabaseURL == "" {
return cfg, fmt.Errorf("DATABASE_URL is required")
}
return cfg, nil
}
func env(key, fallback string) string {
if v := os.Getenv(key); v != "" {
return v
}
return fallback
}
func sessionTTL() time.Duration {
if v := os.Getenv("SESSION_TTL_HOURS"); v != "" {
if h, err := strconv.Atoi(v); err == nil && h > 0 {
return time.Duration(h) * time.Hour
}
}
return 168 * time.Hour
}
func durationEnv(key string, fallback time.Duration) time.Duration {
v := os.Getenv(key)
if v == "" {
return fallback
}
sec, err := strconv.Atoi(v)
if err != nil || sec <= 0 {
return fallback
}
return time.Duration(sec) * time.Second
}