Нема описа
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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. package config
  2. import (
  3. "fmt"
  4. "os"
  5. "path/filepath"
  6. "sync"
  7. "gopkg.in/yaml.v2"
  8. )
  9. // Config 应用配置
  10. type Config struct {
  11. Database DBConfig `yaml:"database"`
  12. Auth Auth `yaml:"auth"`
  13. Service Service `yaml:"service"`
  14. }
  15. // DBConfig 数据库配置
  16. type DBConfig struct {
  17. Type string `yaml:"type"`
  18. Host string `yaml:"host"`
  19. Port int `yaml:"port"`
  20. Username string `yaml:"username"`
  21. Password string `yaml:"password"`
  22. Database string `yaml:"database"`
  23. MaxOpenConns int `yaml:"max_open_conns"`
  24. MaxIdleConns int `yaml:"max_idle_conns"`
  25. ConnMaxLifetime int `yaml:"conn_max_lifetime"` // 单位:秒
  26. }
  27. // Auth 认证配置
  28. type Auth struct {
  29. Token string `yaml:"token"`
  30. }
  31. // Service 微服务配置
  32. type Service struct {
  33. ReadTimeout int `yaml:"read_timeout"`
  34. WriteTimeout int `yaml:"write_timeout"`
  35. IdleTimeout int `yaml:"idle_timeout"`
  36. }
  37. // 导出接口,防止外部修改
  38. type IConfig interface {
  39. GetDatabase() DBConfig
  40. GetAuth() Auth
  41. GetService() Service
  42. IsDatabaseConfigured() bool
  43. }
  44. // 实现接口的具体类型
  45. type configWrapper struct {
  46. config *Config
  47. }
  48. func (cw *configWrapper) GetDatabase() DBConfig {
  49. return cw.config.Database
  50. }
  51. func (cw *configWrapper) GetAuth() Auth {
  52. return cw.config.Auth
  53. }
  54. func (cw *configWrapper) GetService() Service {
  55. return cw.config.Service
  56. }
  57. func (cw *configWrapper) IsDatabaseConfigured() bool {
  58. return cw.config.Database.Type != "" &&
  59. cw.config.Database.Host != "" &&
  60. cw.config.Database.Port > 0 &&
  61. cw.config.Database.Username != "" &&
  62. cw.config.Database.Database != ""
  63. }
  64. func (cw *configWrapper) IsAuthConfigured() bool {
  65. return cw.config.Auth.Token != ""
  66. }
  67. func (cw *configWrapper) IsServiceConfigured() bool {
  68. return cw.config.Service.ReadTimeout > 0 &&
  69. cw.config.Service.WriteTimeout > 0 &&
  70. cw.config.Service.IdleTimeout > 0
  71. }
  72. var (
  73. instance IConfig
  74. once sync.Once
  75. initErr error
  76. )
  77. // GetConfig 获取配置单例实例
  78. func GetConfig() IConfig {
  79. once.Do(func() {
  80. config, err := loadConfig()
  81. if err != nil {
  82. initErr = err
  83. // 创建一个空的配置实例,避免nil指针
  84. instance = &configWrapper{config: &Config{}}
  85. return
  86. }
  87. instance = &configWrapper{config: config}
  88. })
  89. return instance
  90. }
  91. // GetInitError 获取初始化错误(如果有)
  92. func GetInitError() error {
  93. return initErr
  94. }
  95. // loadConfig 加载配置文件
  96. func loadConfig() (*Config, error) {
  97. configFile, err := findConfigFile()
  98. if err != nil {
  99. return nil, err
  100. }
  101. fmt.Printf("✅ Using config file: %s\n", configFile)
  102. // 读取配置文件
  103. data, err := os.ReadFile(configFile)
  104. if err != nil {
  105. return nil, fmt.Errorf("failed to read config file %s: %v", configFile, err)
  106. }
  107. var config Config
  108. err = yaml.Unmarshal(data, &config)
  109. if err != nil {
  110. return nil, fmt.Errorf("failed to parse config file: %v", err)
  111. }
  112. return &config, nil
  113. }
  114. // findConfigFile 查找配置文件
  115. func findConfigFile() (string, error) {
  116. // 1. 首先尝试可执行文件同目录
  117. exePath, err := os.Executable()
  118. if err == nil {
  119. exeDir := filepath.Dir(exePath)
  120. configFile := filepath.Join(exeDir, "db.yaml")
  121. if _, err := os.Stat(configFile); err == nil {
  122. return configFile, nil
  123. }
  124. }
  125. // 2. 尝试环境变量指定的路径
  126. envConfigPath := os.Getenv("DB_CONFIG_PATH")
  127. if envConfigPath != "" {
  128. if _, err := os.Stat(envConfigPath); err == nil {
  129. return envConfigPath, nil
  130. }
  131. return "", fmt.Errorf("DB_CONFIG_PATH file not found: %s", envConfigPath)
  132. }
  133. // 3. 如果都没有找到,返回错误
  134. exeDir := "unknown"
  135. if exePath, err := os.Executable(); err == nil {
  136. exeDir = filepath.Dir(exePath)
  137. }
  138. return "", fmt.Errorf(`No configuration file found!
  139. Tried locations:
  140. 1. Executable directory: %s/db.yaml
  141. 2. Environment variable: DB_CONFIG_PATH
  142. Solutions:
  143. - Place db.yaml in the same directory as the executable
  144. - Or set DB_CONFIG_PATH environment variable to config file path
  145. Example:
  146. export DB_CONFIG_PATH=/path/to/your/db.yaml`, exeDir)
  147. }