diff options
Diffstat (limited to 'backend/internal/config/config.go')
| -rw-r--r-- | backend/internal/config/config.go | 125 |
1 files changed, 125 insertions, 0 deletions
diff --git a/backend/internal/config/config.go b/backend/internal/config/config.go new file mode 100644 index 0000000..60d176e --- /dev/null +++ b/backend/internal/config/config.go @@ -0,0 +1,125 @@ +package config + +import ( + "encoding/json" + "fmt" + "os" + "time" +) + +type Config struct { + Server ServerConfig `json:"server"` + Database DatabaseConfig `json:"database"` + Monitor MonitorConfig `json:"monitor"` + SMTP SMTPConfig `json:"smtp"` + Auth AuthConfig `json:"auth"` +} + +type SMTPConfig struct { + Host string `json:"host"` + Port int `json:"port"` + Username string `json:"username"` + Password string `json:"password"` + From string `json:"from"` +} + +type AuthConfig struct { + AdminUsername string `json:"admin_username"` + AdminPasswordHash string `json:"admin_password_hash"` + JWTSecret string `json:"jwt_secret"` +} + +type ServerConfig struct { + Addr string `json:"addr"` +} + +type DatabaseConfig struct { + URL string `json:"url"` +} + +type MonitorConfig struct { + Interval string `json:"interval"` + Timeout string `json:"timeout"` +} + +func Load(path string) (*Config, error) { + if path == "" { + path = "config.json" + } + + data, err := os.ReadFile(path) + if err != nil { + return nil, fmt.Errorf("ler config %s: %w", path, err) + } + + var cfg Config + if err := json.Unmarshal(data, &cfg); err != nil { + return nil, fmt.Errorf("parse config %s: %w", path, err) + } + + cfg.applyDefaults() + return &cfg, nil +} + +func (c *Config) applyDefaults() { + if c.Server.Addr == "" { + c.Server.Addr = ":8080" + } + if c.Monitor.Interval == "" { + c.Monitor.Interval = "60s" + } + if c.Monitor.Timeout == "" { + c.Monitor.Timeout = "10s" + } +} + +func (c *Config) ServerAddr() string { + if v := os.Getenv("ADDR"); v != "" { + return v + } + return c.Server.Addr +} + +func (c *Config) DatabaseURL() string { + if v := os.Getenv("DATABASE_URL"); v != "" { + return v + } + return c.Database.URL +} + +func (c *Config) CheckInterval() time.Duration { + d, err := time.ParseDuration(c.Monitor.Interval) + if err != nil { + return 60 * time.Second + } + return d +} + +func (c *Config) CheckTimeout() time.Duration { + d, err := time.ParseDuration(c.Monitor.Timeout) + if err != nil { + return 10 * time.Second + } + return d +} + +func (c *Config) AdminUsername() string { + if v := os.Getenv("ADMIN_USERNAME"); v != "" { + return v + } + return c.Auth.AdminUsername +} + +func (c *Config) AdminPasswordHash() string { + if v := os.Getenv("ADMIN_PASSWORD_HASH"); v != "" { + return v + } + return c.Auth.AdminPasswordHash +} + +func (c *Config) JWTSecret() string { + if v := os.Getenv("JWT_SECRET"); v != "" { + return v + } + return c.Auth.JWTSecret +} |