conf.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package conf
  2. import (
  3. "errors"
  4. "flag"
  5. "go-common/library/cache/memcache"
  6. "go-common/library/cache/redis"
  7. "go-common/library/conf"
  8. "go-common/library/database/sql"
  9. ecode "go-common/library/ecode/tip"
  10. "go-common/library/log"
  11. bm "go-common/library/net/http/blademaster"
  12. "go-common/library/net/http/blademaster/middleware/auth"
  13. "go-common/library/net/http/blademaster/middleware/verify"
  14. "go-common/library/net/trace"
  15. "github.com/BurntSushi/toml"
  16. )
  17. var (
  18. confPath string
  19. client *conf.Client
  20. // Conf config
  21. Conf = &Config{}
  22. )
  23. // Config .
  24. type Config struct {
  25. Log *log.Config
  26. BM *bm.ServerConfig
  27. Verify *verify.Config
  28. Auth *auth.Config
  29. Tracer *trace.Config
  30. Redis *redis.Config
  31. Memcache *memcache.Config
  32. MySQL *sql.Config
  33. TIDB *sql.Config
  34. Ecode *ecode.Config
  35. // http client
  36. HTTPClient *bm.ClientConfig
  37. DropCDN map[string]interface{}
  38. }
  39. func init() {
  40. flag.StringVar(&confPath, "conf", "", "default config path")
  41. }
  42. // Init init conf
  43. func Init() error {
  44. if confPath != "" {
  45. return local()
  46. }
  47. return remote()
  48. }
  49. func local() (err error) {
  50. _, err = toml.DecodeFile(confPath, &Conf)
  51. return
  52. }
  53. func remote() (err error) {
  54. if client, err = conf.New(); err != nil {
  55. return
  56. }
  57. if err = load(); err != nil {
  58. return
  59. }
  60. go func() {
  61. for range client.Event() {
  62. log.Info("config reload")
  63. if load() != nil {
  64. log.Error("config reload error (%v)", err)
  65. }
  66. }
  67. }()
  68. return
  69. }
  70. func load() (err error) {
  71. var (
  72. s string
  73. ok bool
  74. tmpConf *Config
  75. )
  76. if s, ok = client.Toml2(); !ok {
  77. return errors.New("load config center error")
  78. }
  79. if _, err = toml.Decode(s, &tmpConf); err != nil {
  80. return errors.New("could not decode config")
  81. }
  82. *Conf = *tmpConf
  83. return
  84. }