// Package config 应用配置 package config import ( "fmt" "os" "gopkg.in/yaml.v3" ) // AppConfig 应用配置 var AppConfig = &appConfig{} type appConfig struct { Log LogConfig `yaml:"log"` Security SecurityConfig `yaml:"security"` RateLimit RateLimitConfig `yaml:"rate_limit"` Swagger SwaggerConfig `yaml:"swagger"` Database DatabaseConfig `yaml:"database"` Redis RedisConfig `yaml:"redis"` } // LogConfig 日志配置 type LogConfig struct { Level string `yaml:"level"` // 日志级别 Dir string `yaml:"dir"` // 日志目录 Console bool `yaml:"console"` // 是否输出到控制台 } // SecurityConfig 安全配置 type SecurityConfig struct { Enable bool `yaml:"enable"` // 是否启用 HeaderKey string `yaml:"header_key"` // 请求头字段名 SecretKey string `yaml:"secret_key"` // 签名密钥 } // RateLimitConfig 限流配置 type RateLimitConfig struct { Enable bool `yaml:"enable"` // 是否启用 Default RateLimitRule `yaml:"default"` // 默认规则 Rules map[string]RateLimitRule `yaml:"rules"` // 特定路径规则 } // RateLimitRule 限流规则 type RateLimitRule struct { Interval int `yaml:"interval"` // 时间间隔(秒) MaxRequests int `yaml:"max_requests"` // 最大请求次数 } // SwaggerConfig Swagger文档认证配置 type SwaggerConfig struct { User string `yaml:"user"` Password string `yaml:"password"` } // DatabaseConfig 数据库配置 type DatabaseConfig struct { Driver string `yaml:"driver"` Host string `yaml:"host"` Port int `yaml:"port"` Database string `yaml:"database"` Username string `yaml:"username"` Password string `yaml:"password"` Charset string `yaml:"charset"` MaxIdleConns int `yaml:"max_idle_conns"` MaxOpenConns int `yaml:"max_open_conns"` ConnMaxLifetime int `yaml:"conn_max_lifetime"` // 小时 LogMode bool `yaml:"log_mode"` // 是否开启SQL日志 } // RedisConfig Redis配置 type RedisConfig struct { Addr string `yaml:"addr"` Password string `yaml:"password"` DB int `yaml:"db"` } // LoadConfig 加载配置 func LoadConfig() { var configFile string // 1. 优先检查命令行参数 (简单解析) // 格式: ./app -c config.prod.yaml 或 ./app -config config.prod.yaml args := os.Args for i, arg := range args { if (arg == "-c" || arg == "-config") && i+1 < len(args) { configFile = args[i+1] break } } // 2. 如果命令行参数未指定,则根据环境变量查找 if configFile == "" { env := os.Getenv("GO_ENV") if env == "" { env = "dev" } // 查找顺序: // 1. 当前目录 config.{env}.yaml (方便部署时直接放在执行文件旁) // 2. config/config.{env}.yaml (开发习惯) // 3. ../config/config.{env}.yaml (测试环境习惯) searchPaths := []string{ fmt.Sprintf("config.%s.yaml", env), fmt.Sprintf("config/config.%s.yaml", env), fmt.Sprintf("../config/config.%s.yaml", env), } for _, path := range searchPaths { if _, err := os.Stat(path); err == nil { configFile = path break } } // 如果都没找到,默认回退到 config/config.{env}.yaml 以便报错信息准确 if configFile == "" { configFile = fmt.Sprintf("config/config.%s.yaml", env) } } fmt.Printf("正在加载配置文件: %s\n", configFile) data, err := os.ReadFile(configFile) if err != nil { fmt.Printf("读取配置文件失败: %v, 使用默认配置\n", err) return } err = yaml.Unmarshal(data, AppConfig) if err != nil { fmt.Printf("解析配置文件失败: %v\n", err) panic(err) } }