暂无描述
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

config.go 3.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  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. data, err := os.ReadFile(configFile)
  101. if err != nil {
  102. return nil, fmt.Errorf("failed to read config file %s: %v", configFile, err)
  103. }
  104. var config Config
  105. err = yaml.Unmarshal(data, &config)
  106. if err != nil {
  107. return nil, fmt.Errorf("failed to parse config file: %v", err)
  108. }
  109. return &config, nil
  110. }
  111. // findConfigFile 查找配置文件
  112. func findConfigFile() (string, error) {
  113. // 1. 首先尝试可执行文件同目录
  114. exePath, err := os.Executable()
  115. if err == nil {
  116. exeDir := filepath.Dir(exePath)
  117. configFile := filepath.Join(exeDir, "db.yaml")
  118. if _, err := os.Stat(configFile); err == nil {
  119. return configFile, nil
  120. }
  121. }
  122. // 2. 尝试环境变量指定的路径
  123. envConfigPath := os.Getenv("DB_CONFIG_PATH")
  124. if envConfigPath != "" {
  125. if _, err := os.Stat(envConfigPath); err == nil {
  126. return envConfigPath, nil
  127. }
  128. return "", fmt.Errorf("DB_CONFIG_PATH file not found: %s", envConfigPath)
  129. }
  130. // 3. 如果都没有找到,返回错误
  131. exeDir := "unknown"
  132. if exePath, err := os.Executable(); err == nil {
  133. exeDir = filepath.Dir(exePath)
  134. }
  135. return "", fmt.Errorf(`No configuration file found!
  136. Tried locations:
  137. 1. Executable directory: %s/db.yaml
  138. 2. Environment variable: DB_CONFIG_PATH
  139. Solutions:
  140. - Place db.yaml in the same directory as the executable
  141. - Or set DB_CONFIG_PATH environment variable to config file path
  142. Example:
  143. export DB_CONFIG_PATH=/path/to/your/db.yaml`, exeDir)
  144. }