| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192 |
- package subconfigs
-
- import (
- "fmt"
- "log"
- )
-
- // DbConfig 单个数据库配置(共享结构)
- type DbConfig struct {
- Type string `yaml:"type" desc:"数据库类型,如:mysql、postgresql"`
- Host string `yaml:"host" desc:"数据库主机地址"`
- Port int `yaml:"port" desc:"数据库端口"`
- Username string `yaml:"username" desc:"数据库用户名"`
- Password string `yaml:"password" desc:"数据库密码"`
- Database string `yaml:"database" desc:"数据库名称"`
- MaxOpenConns int `yaml:"max_open_conns" desc:"最大打开连接数"`
- MaxIdleConns int `yaml:"max_idle_conns" desc:"最大空闲连接数"`
- ConnMaxLifetime int `yaml:"conn_max_lifetime" desc:"连接最大生命周期(秒)"`
- }
-
- // SetDbDefaults 设置数据库配置默认值
- func SetDbDefaults(c *DbConfig) {
- 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
- }
- }
-
- // ValidateDbConfig 验证数据库配置
- func ValidateDbConfig(c *DbConfig) 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
- }
-
- // IsDbConfigured 判断数据库是否已配置
- func IsDbConfigured(c *DbConfig, name string) bool {
- if c.Host == "" {
- if name != "" {
- log.Printf("⚠️ 警告: 数据库 '%s' Host 未配置", name)
- } else {
- log.Println("⚠️ 警告: 数据库 Host 未配置")
- }
- return false
- }
- if c.Port <= 0 {
- if name != "" {
- log.Printf("⚠️ 警告: 数据库 '%s' Port 未配置或无效", name)
- } else {
- log.Println("⚠️ 警告: 数据库 Port 未配置或无效")
- }
- return false
- }
- if c.Username == "" {
- if name != "" {
- log.Printf("⚠️ 警告: 数据库 '%s' Username 未配置", name)
- } else {
- log.Println("⚠️ 警告: 数据库 Username 未配置")
- }
- return false
- }
- if c.Database == "" {
- if name != "" {
- log.Printf("⚠️ 警告: 数据库 '%s' 名称未配置", name)
- } else {
- log.Println("⚠️ 警告: 数据库名称未配置")
- }
- return false
- }
- return true
- }
|