| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788 |
- package subconfigs
-
- import (
- "fmt"
- "log"
- )
-
- // DatabaseConfig 数据库配置
- type DatabaseConfig struct {
- BaseConfig
- Type string `yaml:"type"`
- Host string `yaml:"host"`
- Port int `yaml:"port"`
- Username string `yaml:"username"`
- Password string `yaml:"password"`
- Database string `yaml:"database"`
- MaxOpenConns int `yaml:"max_open_conns"`
- MaxIdleConns int `yaml:"max_idle_conns"`
- ConnMaxLifetime int `yaml:"conn_max_lifetime"`
- }
-
- // SetDefaults 设置默认值 - 实现 ConfigLoader 接口
- func (c *DatabaseConfig) SetDefaults() {
- if c.Type == "" {
- c.Type = "mysql"
- }
- if c.Port == 0 {
- c.Port = 3306
- }
- if c.MaxOpenConns == 0 {
- c.MaxOpenConns = 100
- }
- if c.MaxIdleConns == 0 {
- c.MaxIdleConns = 20
- }
- if c.ConnMaxLifetime == 0 {
- c.ConnMaxLifetime = 3600
- }
- }
-
- // Load 从yaml数据加载 - 实现 ConfigLoader 接口
- func (c *DatabaseConfig) Load(data map[string]interface{}) error {
-
- return c.LoadFromYAML(data, c)
- }
-
- // Validate 验证配置(数据库配置)
- func (c *DatabaseConfig) Validate() error {
- if c.Type == "" {
- return fmt.Errorf("database type is required")
- }
- if c.Host == "" {
- return fmt.Errorf("database host is required")
- }
- if c.Port <= 0 || c.Port > 65535 {
- return fmt.Errorf("invalid database port: %d", c.Port)
- }
- if c.Database == "" {
- return fmt.Errorf("database name is required")
- }
- return nil
- }
-
- // IsConfigured 判断是否已配置(数据库配置)
- func (c *DatabaseConfig) IsConfigured() bool {
- if c.Host == "" {
- log.Println("⚠️ 警告: 数据库 Host 未配置")
- return false
- }
- if c.Port <= 0 {
- log.Println("⚠️ 警告: 数据库 Port 未配置或无效")
- return false
- }
- if c.Username == "" {
- log.Println("⚠️ 警告: 数据库 Username 未配置")
- return false
- }
- if c.Database == "" {
- log.Println("⚠️ 警告: 数据库名称未配置")
- return false
- }
- return true
- }
-
- // 自动注册
- func init() {
- Register("database", &DatabaseConfig{})
- }
|