package config import ( "fmt" "log" "os" "path/filepath" "git.x2erp.com/qdy/go-base/config/subconfigs" "gopkg.in/yaml.v2" ) // LoadConfig 从文件加载配置到注册表(保持原有接口不变) func LoadConfig() { // 1. 查找配置文件 configFile, err := findConfigFile() if err != nil { log.Fatalf("查找配置文件错误:%v", err) } // 2. 读取并解析文件 data, err := os.ReadFile(configFile) if err != nil { log.Fatalf("read config file error: %v", err) } var rawConfig map[string]interface{} err = yaml.Unmarshal(data, &rawConfig) if err != nil { log.Fatalf("parse yaml error: %v", err) } // 3. 从map加载配置 LoadConfigFromMap(rawConfig) } // LoadConfigFromMap 从map[string]interface{}加载配置到注册表 // 新增方法,供外部调用(比如从数据库加载后使用) func LoadConfigFromMap(rawConfig map[string]interface{}) { // 1. 设置所有注册配置的默认值 for _, config := range subconfigs.GetAllConfigs() { config.SetDefaults() } // 2. 循环注册表,为每个配置加载数据 for name, config := range subconfigs.GetAllConfigs() { if configData, ok := rawConfig[name].(map[interface{}]interface{}); ok { // 转换为 map[string]interface{} strMap := convertMap(configData) if err := config.Load(strMap); err != nil { log.Fatalf("load config %s error: %v", name, err) } } } } // convertMap 转换map类型(内部函数保持不变) func convertMap(input map[interface{}]interface{}) map[string]interface{} { output := make(map[string]interface{}) for k, v := range input { if strKey, ok := k.(string); ok { output[strKey] = v } } return output } // findConfigFile 查找配置文件(内部函数保持不变) func findConfigFile() (string, error) { exePath, _ := os.Executable() exeDir := filepath.Dir(exePath) possiblePaths := []string{ filepath.Join(exeDir, "db.yaml"), filepath.Join(exeDir, "config", "db.yaml"), "db.yaml", "config/db.yaml", os.Getenv("DB_CONFIG_PATH"), } for _, path := range possiblePaths { if path == "" { continue } if _, err := os.Stat(path); err == nil { log.Printf("✅ Using config file: %s\n", path) return path, nil } } return "", fmt.Errorf(`no configuration file found Searched locations: 1. %s 2. %s 3. ./db.yaml 4. ./config/db.yaml 5. DB_CONFIG_PATH环境变量指定的路径 请确保配置文件存在,或通过环境变量指定: export DB_CONFIG_PATH=/your/config/path/db.yaml set DB_CONFIG_PATH=C:\your\config\path\db.yaml (Windows)`, filepath.Join(exeDir, "db.yaml"), filepath.Join(exeDir, "config", "db.yaml")) }