package config import ( "fmt" "github.com/spf13/viper" ) // GlobalConfig 全局配置实例 var GlobalConfig Config type Config struct { App AppConfig `mapstructure:"app"` Database DatabaseConfig `mapstructure:"database"` } type AppConfig struct { MaxCo int `mapstructure:"max_co"` Debug bool `mapstructure:"debug"` // 新增 Debug 字段 } type DatabaseConfig struct { DSN string `mapstructure:"dsn"` MaxOpenConns int `mapstructure:"max_open_conns"` MaxIdleConns int `mapstructure:"max_idle_conns"` ConnMaxLifetime int `mapstructure:"conn_max_lifetime"` ConnMaxIdleTime int `mapstructure:"conn_max_idle_time"` } // InitConfig 初始化并读取 YAML 配置文件 func InitConfig(cfgFile string) error { if cfgFile != "" { // 如果命令行指定了配置文件路径 viper.SetConfigFile(cfgFile) } else { // 默认在当前目录下查找 config.yaml viper.AddConfigPath(".") viper.SetConfigType("yaml") viper.SetConfigName("config") } if err := viper.ReadInConfig(); err != nil { return fmt.Errorf("读取配置文件失败: %w", err) } // 解析到结构体 if err := viper.Unmarshal(&GlobalConfig); err != nil { return fmt.Errorf("解析配置文件结构失败: %w", err) } return nil }