package storage import ( "errors" "strings" "time" mysqldriver "github.com/go-sql-driver/mysql" ) type Config struct { Mysql ConfigMysql `mapstructure:"mysql"` Redis ConfigRedis `mapstructure:"redis"` } type ConfigMysql struct { Enabled bool `mapstructure:"enabled"` DSN string `mapstructure:"dsn"` ShowSQL bool `mapstructure:"show_sql"` MaxOpenConn int `mapstructure:"max_open_conn"` MaxIdleConn int `mapstructure:"max_idle_conn"` ConnMaxLifetime time.Duration `mapstructure:"conn_max_lifetime"` ConnectTimeout time.Duration `mapstructure:"connect_timeout"` } type ConfigRedis struct { Enabled bool `mapstructure:"enabled"` Addr string `mapstructure:"addr"` Password string `mapstructure:"password"` DB int `mapstructure:"db"` ConnectTimeout time.Duration `mapstructure:"connect_timeout"` } func (cfg Config) Validate() error { if cfg.Mysql.Enabled { mysql := cfg.Mysql if strings.TrimSpace(mysql.DSN) == "" { return errors.New("storage.mysql.dsn is required when mysql is enabled") } if _, err := mysqldriver.ParseDSN(mysql.DSN); err != nil { return errors.New("storage.mysql.dsn is invalid") } if mysql.MaxOpenConn <= 0 || mysql.MaxIdleConn < 0 || mysql.MaxIdleConn > mysql.MaxOpenConn { return errors.New("mysql connection pool requires max_open_conn > 0 and 0 <= max_idle_conn <= max_open_conn") } if mysql.ConnMaxLifetime <= 0 || mysql.ConnectTimeout <= 0 { return errors.New("mysql connection durations must be greater than zero") } } if cfg.Redis.Enabled && (strings.TrimSpace(cfg.Redis.Addr) == "" || cfg.Redis.DB < 0 || cfg.Redis.ConnectTimeout <= 0) { return errors.New("enabled redis requires addr, non-negative db and positive connect_timeout") } return nil }