package config import ( "net/http" "strings" "time" "github.com/spf13/viper" "go.uber.org/multierr" "gitea.privcloud.tech/mtusi2026/internal/pkg/environment" ) var defaultConfig = &Config{ Server: &Server{ Host: "localhost", Port: 8001, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, IdleTimeout: 10 * time.Second, ShutdownTimeout: 10 * time.Second, Enabled: false, }, Postgres: &Postgres{ Host: "localhost", Port: 5432, User: "postgres", Password: "postgres", Database: "postgres", VersionTable: "versions", RunMigrations: false, MaxConnections: 10, }, Redis: &Redis{ Host: "localhost", Port: 6379, Username: "", Password: "", DB: 0, }, JWT: &JWT{ AccessTokenLifetime: 4 * time.Hour, RefreshTokenLifetime: 24 * time.Hour, PublicKeyPath: "certs/private.pem", PrivateKeyPath: "certs/public.pem", }, Cookies: &Cookies{ Enabled: true, Domain: "", Path: "/", Secure: true, SameSite: http.SameSiteStrictMode, AllowedOrigins: []string{"http:localhost:8080"}, }, Application: &Application{ LogLevel: "info", ShutdownTimeout: 10 * time.Second, Environment: environment.ApplicationEnvironmentDev, RequestRateLimit: 100, }, } type Config struct { Server *Server Postgres *Postgres Redis *Redis JWT *JWT Cookies *Cookies Application *Application } func New() (*Config, error) { v := viper.New() v.SetEnvKeyReplacer(strings.NewReplacer(".", "_")) v.AutomaticEnv() cfg := defaultConfig.copy() if err := cfg.loadConfig(v); err != nil { return nil, err } if err := cfg.Validate(); err != nil { return nil, err } return cfg, nil } func (c *Config) Validate() error { return multierr.Combine( c.Server.Validate(), c.Postgres.Validate(), c.JWT.Validate(), c.Redis.Validate(), c.Cookies.Validate(), c.Application.Validate(), ) } func (c *Config) loadConfig(v *viper.Viper) error { return multierr.Combine( c.Postgres.loadConfig(v), c.Server.loadConfig(v), c.JWT.loadConfig(v), c.Redis.loadConfig(v), c.Cookies.loadConfig(v), c.Application.loadConfig(v), ) } func (c *Config) copy() *Config { return &Config{ Server: c.Server.copy(), Postgres: c.Postgres.copy(), Redis: c.Redis.copy(), JWT: c.JWT.copy(), Cookies: c.Cookies.copy(), Application: c.Application.copy(), } }