conf.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. package conf
  2. import (
  3. "errors"
  4. "flag"
  5. "go-common/library/cache/memcache"
  6. "go-common/library/conf"
  7. "go-common/library/database/sql"
  8. "go-common/library/log"
  9. bm "go-common/library/net/http/blademaster"
  10. "go-common/library/net/http/blademaster/middleware/verify"
  11. "go-common/library/net/trace"
  12. xtime "go-common/library/time"
  13. "github.com/BurntSushi/toml"
  14. )
  15. var (
  16. confPath string
  17. // Conf all configs
  18. Conf = &Config{}
  19. client *conf.Client
  20. )
  21. // Config all config
  22. type Config struct {
  23. // Env
  24. Env string
  25. // interface XLog
  26. XLog *log.Config
  27. // bm
  28. BM *bm.ServerConfig
  29. // tracer
  30. Tracer *trace.Config
  31. // db
  32. Mysql *sql.Config
  33. // mc
  34. Memcache *Memcache
  35. // host
  36. Host *Host
  37. // verify
  38. Verify *verify.Config
  39. }
  40. // Host host config
  41. type Host struct {
  42. Default string
  43. QuanZi string
  44. }
  45. // Memcache memcache config
  46. type Memcache struct {
  47. *memcache.Config
  48. Expire xtime.Duration
  49. }
  50. func init() {
  51. flag.StringVar(&confPath, "conf", "", "default config path")
  52. }
  53. // Init init config.
  54. func Init() (err error) {
  55. if confPath != "" {
  56. _, err = toml.DecodeFile(confPath, &Conf)
  57. return
  58. }
  59. err = remote()
  60. return
  61. }
  62. func remote() (err error) {
  63. if client, err = conf.New(); err != nil {
  64. return
  65. }
  66. if err = load(); err != nil {
  67. return
  68. }
  69. go func() {
  70. for range client.Event() {
  71. log.Info("config reload")
  72. if load() != nil {
  73. log.Error("config reload error (%v)", err)
  74. }
  75. }
  76. }()
  77. return
  78. }
  79. func load() (err error) {
  80. var (
  81. s string
  82. ok bool
  83. tmpConf *Config
  84. )
  85. if s, ok = client.Toml2(); !ok {
  86. return errors.New("load config center error")
  87. }
  88. if _, err = toml.Decode(s, &tmpConf); err != nil {
  89. return errors.New("could not decode config")
  90. }
  91. *Conf = *tmpConf
  92. return
  93. }