config.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. package config
  2. import (
  3. "fmt"
  4. "log"
  5. "gogs.baozhida.cn/zoie/OAuth-core/config"
  6. "gogs.baozhida.cn/zoie/OAuth-core/config/source"
  7. )
  8. var (
  9. ExtendConfig interface{}
  10. _cfg *Settings
  11. )
  12. // Settings 兼容原先的配置结构
  13. type Settings struct {
  14. Settings Config `yaml:"settings"`
  15. callbacks []func()
  16. }
  17. func (e *Settings) runCallback() {
  18. for i := range e.callbacks {
  19. e.callbacks[i]()
  20. }
  21. }
  22. func (e *Settings) OnChange() {
  23. e.init()
  24. log.Println("!!! config change and reload")
  25. }
  26. func (e *Settings) Init() {
  27. e.init()
  28. log.Println("!!! config init")
  29. }
  30. func (e *Settings) init() {
  31. e.Settings.Logger.Setup()
  32. e.Settings.multiDatabase()
  33. e.runCallback()
  34. }
  35. // Config 配置集合
  36. type Config struct {
  37. Application *Application `yaml:"application"`
  38. Ssl *Ssl `yaml:"ssl"`
  39. Logger *Logger `yaml:"logger"`
  40. Jwt *Jwt `yaml:"jwt"`
  41. Database *Database `yaml:"database"`
  42. Databases *map[string]*Database `yaml:"databases"`
  43. Gen *Gen `yaml:"gen"`
  44. Cache *Cache `yaml:"cache"`
  45. Queue *Queue `yaml:"queue"`
  46. Locker *Locker `yaml:"locker"`
  47. Extend interface{} `yaml:"extend"`
  48. }
  49. // 多db改造
  50. func (e *Config) multiDatabase() {
  51. if len(*e.Databases) == 0 {
  52. *e.Databases = map[string]*Database{
  53. "*": e.Database,
  54. }
  55. }
  56. }
  57. // Setup 载入配置文件
  58. func Setup(s source.Source,
  59. fs ...func()) {
  60. _cfg = &Settings{
  61. Settings: Config{
  62. Application: ApplicationConfig,
  63. Ssl: SslConfig,
  64. Logger: LoggerConfig,
  65. Jwt: JwtConfig,
  66. Database: DatabaseConfig,
  67. Databases: &DatabasesConfig,
  68. Gen: GenConfig,
  69. Cache: CacheConfig,
  70. Queue: QueueConfig,
  71. Locker: LockerConfig,
  72. Extend: ExtendConfig,
  73. },
  74. callbacks: fs,
  75. }
  76. var err error
  77. config.DefaultConfig, err = config.NewConfig(
  78. config.WithSource(s),
  79. config.WithEntity(_cfg),
  80. )
  81. if err != nil {
  82. log.Fatal(fmt.Sprintf("New config object fail: %s", err.Error()))
  83. }
  84. _cfg.Init()
  85. }