| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495 |
- package config
-
- import (
- "fmt"
- "log"
- "os"
- "path/filepath"
-
- "git.x2erp.com/qdy/go-base/config/subconfigs"
- "gopkg.in/yaml.v2"
- )
-
- // LoadConfig 加载配置到注册表
- func LoadConfig() error {
- // 1. 设置所有注册配置的默认值
- for _, config := range subconfigs.GetAllConfigs() {
- config.SetDefaults()
- }
-
- // 2. 查找配置文件
- configFile, err := findConfigFile()
- if err != nil {
- return err
- }
-
- // 3. 读取文件
- data, err := os.ReadFile(configFile)
- if err != nil {
- return fmt.Errorf("read config file error: %v", err)
- }
-
- // 4. 解析为map
- var rawConfig map[string]interface{}
- err = yaml.Unmarshal(data, &rawConfig)
- if err != nil {
- return fmt.Errorf("parse yaml error: %v", err)
- }
-
- // 5. 循环注册表,为每个配置加载数据
- 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 {
- return fmt.Errorf("load config %s error: %v", name, err)
- }
- }
- }
-
- // // 6. 验证所有配置
- // for name, config := range subconfigs.GetAllConfigs() {
- // if err := config.Validate(); err != nil {
- // return fmt.Errorf("validate config %s error: %v", name, err)
- // }
- // }
-
- return nil
- }
-
- // 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")
- }
|