Нет описания
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  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. Port int `yaml:"port"`
  34. ReadTimeout int `yaml:"read_timeout"`
  35. WriteTimeout int `yaml:"write_timeout"`
  36. IdleTimeout int `yaml:"idle_timeout"`
  37. TrustedProxies string `yaml:"trusted_proxies"`
  38. }
  39. // 导出接口,防止外部修改
  40. type IConfig interface {
  41. GetDatabase() DBConfig
  42. GetAuth() Auth
  43. GetService() Service
  44. IsDatabaseConfigured() bool
  45. }
  46. // 实现接口的具体类型
  47. type configWrapper struct {
  48. config *Config
  49. }
  50. func (cw *configWrapper) GetDatabase() DBConfig {
  51. return cw.config.Database
  52. }
  53. func (cw *configWrapper) GetAuth() Auth {
  54. return cw.config.Auth
  55. }
  56. func (cw *configWrapper) GetService() Service {
  57. return cw.config.Service
  58. }
  59. func (cw *configWrapper) IsDatabaseConfigured() bool {
  60. return cw.config.Database.Type != "" &&
  61. cw.config.Database.Host != "" &&
  62. cw.config.Database.Port > 0 &&
  63. cw.config.Database.Username != "" &&
  64. cw.config.Database.Database != ""
  65. }
  66. func (cw *configWrapper) IsAuthConfigured() bool {
  67. return cw.config.Auth.Token != ""
  68. }
  69. var (
  70. instance IConfig
  71. once sync.Once
  72. initErr error
  73. )
  74. // GetConfig 获取配置单例实例
  75. func GetConfig() IConfig {
  76. once.Do(func() {
  77. config, err := loadConfig()
  78. if err != nil {
  79. initErr = err
  80. // 创建一个空的配置实例,避免nil指针
  81. instance = &configWrapper{config: &Config{}}
  82. return
  83. }
  84. instance = &configWrapper{config: config}
  85. })
  86. return instance
  87. }
  88. // GetInitError 获取初始化错误(如果有)
  89. func GetInitError() error {
  90. return initErr
  91. }
  92. // loadConfig 加载配置文件
  93. func loadConfig() (*Config, error) {
  94. configFile, err := findConfigFile()
  95. if err != nil {
  96. return nil, err
  97. }
  98. fmt.Printf("✅ Using config file: %s\n", configFile)
  99. // 先创建带默认值的配置
  100. config := &Config{
  101. Service: Service{
  102. Port: 8080,
  103. ReadTimeout: 30,
  104. WriteTimeout: 30,
  105. IdleTimeout: 60,
  106. TrustedProxies: "",
  107. },
  108. }
  109. // 读取配置文件
  110. data, err := os.ReadFile(configFile)
  111. if err != nil {
  112. return nil, fmt.Errorf("failed to read config file %s: %v", configFile, err)
  113. }
  114. err = yaml.Unmarshal(data, &config)
  115. if err != nil {
  116. return nil, fmt.Errorf("failed to parse config file: %v", err)
  117. }
  118. return config, nil
  119. }
  120. // findConfigFile 查找配置文件
  121. func findConfigFile() (string, error) {
  122. // 1. 首先尝试可执行文件同目录
  123. exePath, err := os.Executable()
  124. if err == nil {
  125. exeDir := filepath.Dir(exePath)
  126. configFile := filepath.Join(exeDir, "db.yaml")
  127. if _, err := os.Stat(configFile); err == nil {
  128. return configFile, nil
  129. }
  130. }
  131. // 2. 尝试环境变量指定的路径
  132. envConfigPath := os.Getenv("DB_CONFIG_PATH")
  133. if envConfigPath != "" {
  134. if _, err := os.Stat(envConfigPath); err == nil {
  135. return envConfigPath, nil
  136. }
  137. return "", fmt.Errorf("DB_CONFIG_PATH file not found: %s", envConfigPath)
  138. }
  139. // 3. 如果都没有找到,返回错误
  140. exeDir := "unknown"
  141. if exePath, err := os.Executable(); err == nil {
  142. exeDir = filepath.Dir(exePath)
  143. }
  144. return "", fmt.Errorf(`no configuration file found!
  145. Tried locations:
  146. 1. Executable directory: %s/db.yaml
  147. 2. Environment variable: DB_CONFIG_PATH
  148. Solutions:
  149. - Place db.yaml in the same directory as the executable
  150. - Or set DB_CONFIG_PATH environment variable to config file path
  151. Example:
  152. export DB_CONFIG_PATH=/path/to/your/db.yaml`, exeDir)
  153. }