| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110 |
- 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")
-
- 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"))
- }
|