Files
aiaa-notification-server/internal/config/config.go
T

109 lines
2.6 KiB
Go

package config
import (
"fmt"
"os"
"strings"
"github.com/spf13/viper"
)
type Config struct {
Server ServerConfig `mapstructure:"server"`
Database DatabaseConfig `mapstructure:"database"`
Redis RedisConfig `mapstructure:"redis"`
SMTP SMTPConfig `mapstructure:"smtp"`
RateLimit RateLimitConfig `mapstructure:"rate_limit"`
Logbull LogbullConfig `mapstructure:"logbull"`
}
type ServerConfig struct {
Port int `mapstructure:"port"`
AdminKey string `mapstructure:"admin_key"`
}
type DatabaseConfig struct {
Host string `mapstructure:"host"`
Port int `mapstructure:"port"`
User string `mapstructure:"user"`
Password string `mapstructure:"password"`
Database string `mapstructure:"database"`
}
func (d DatabaseConfig) DSN() string {
return fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=true&loc=Local",
d.User, d.Password, d.Host, d.Port, d.Database)
}
type RedisConfig struct {
Host string `mapstructure:"host"`
Port int `mapstructure:"port"`
Password string `mapstructure:"password"`
DB int `mapstructure:"db"`
}
func (r RedisConfig) Addr() string {
return fmt.Sprintf("%s:%d", r.Host, r.Port)
}
type SMTPConfig struct {
Host string `mapstructure:"host"`
Port int `mapstructure:"port"`
User string `mapstructure:"user"`
Password string `mapstructure:"password"`
From string `mapstructure:"from"`
}
type RateLimitConfig struct {
Default int `mapstructure:"default"`
}
type LogbullConfig struct {
Host string `mapstructure:"host"`
ProjectID string `mapstructure:"project_id"`
APIKey string `mapstructure:"api_key"`
LogLevel string `mapstructure:"log_level"`
}
func Load(path string) (*Config, error) {
v := viper.New()
v.SetConfigFile(path)
v.SetEnvPrefix("NOTIFY")
v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
v.AutomaticEnv()
if err := v.ReadInConfig(); err != nil {
return nil, fmt.Errorf("read config: %w", err)
}
// Expand ${ENV_VAR} placeholders in config values
for _, key := range v.AllKeys() {
val := v.GetString(key)
if strings.Contains(val, "${") {
expanded := expandEnv(val)
v.Set(key, expanded)
}
}
var cfg Config
if err := v.Unmarshal(&cfg); err != nil {
return nil, fmt.Errorf("unmarshal config: %w", err)
}
return &cfg, nil
}
func expandEnv(s string) string {
return os.Expand(s, func(key string) string {
// support ${VAR:-default}
if i := strings.Index(key, ":-"); i >= 0 {
name := key[:i]
def := key[i+2:]
if v, ok := os.LookupEnv(name); ok {
return v
}
return def
}
return os.Getenv(key)
})
}