暫無描述
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

loader.go 2.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package config
  2. import (
  3. "fmt"
  4. "os"
  5. "path/filepath"
  6. "git.x2erp.com/qdy/go-base/config/subconfigs"
  7. "gopkg.in/yaml.v2"
  8. )
  9. // LoadConfig 加载配置到注册表
  10. func LoadConfig() error {
  11. // 1. 设置所有注册配置的默认值
  12. for _, config := range subconfigs.GetAllConfigs() {
  13. config.SetDefaults()
  14. }
  15. // 2. 查找配置文件
  16. configFile, err := findConfigFile()
  17. if err != nil {
  18. return err
  19. }
  20. // 3. 读取文件
  21. data, err := os.ReadFile(configFile)
  22. if err != nil {
  23. return fmt.Errorf("read config file error: %v", err)
  24. }
  25. // 4. 解析为map
  26. var rawConfig map[string]interface{}
  27. err = yaml.Unmarshal(data, &rawConfig)
  28. if err != nil {
  29. return fmt.Errorf("parse yaml error: %v", err)
  30. }
  31. // 5. 循环注册表,为每个配置加载数据
  32. for name, config := range subconfigs.GetAllConfigs() {
  33. if configData, ok := rawConfig[name].(map[interface{}]interface{}); ok {
  34. // 转换为 map[string]interface{}
  35. strMap := convertMap(configData)
  36. if err := config.Load(strMap); err != nil {
  37. return fmt.Errorf("load config %s error: %v", name, err)
  38. }
  39. }
  40. }
  41. // // 6. 验证所有配置
  42. // for name, config := range subconfigs.GetAllConfigs() {
  43. // if err := config.Validate(); err != nil {
  44. // return fmt.Errorf("validate config %s error: %v", name, err)
  45. // }
  46. // }
  47. return nil
  48. }
  49. // convertMap 转换map类型
  50. func convertMap(input map[interface{}]interface{}) map[string]interface{} {
  51. output := make(map[string]interface{})
  52. for k, v := range input {
  53. if strKey, ok := k.(string); ok {
  54. output[strKey] = v
  55. }
  56. }
  57. return output
  58. }
  59. // findConfigFile 查找配置文件
  60. func findConfigFile() (string, error) {
  61. exePath, _ := os.Executable()
  62. exeDir := filepath.Dir(exePath)
  63. possiblePaths := []string{
  64. filepath.Join(exeDir, "db.yaml"),
  65. filepath.Join(exeDir, "config", "db.yaml"),
  66. "db.yaml",
  67. "config/db.yaml",
  68. os.Getenv("DB_CONFIG_PATH"),
  69. }
  70. for _, path := range possiblePaths {
  71. if path == "" {
  72. continue
  73. }
  74. if _, err := os.Stat(path); err == nil {
  75. fmt.Printf("✅ Using config file: %s\n", path)
  76. return path, nil
  77. }
  78. }
  79. return "", fmt.Errorf("no configuration file found")
  80. }