conf.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. package conf
  2. import (
  3. "errors"
  4. "flag"
  5. "go-common/library/net/rpc/warden"
  6. "go-common/library/cache/memcache"
  7. "go-common/library/cache/redis"
  8. "go-common/library/conf"
  9. "go-common/library/database/sql"
  10. ecode "go-common/library/ecode/tip"
  11. "go-common/library/log"
  12. bm "go-common/library/net/http/blademaster"
  13. "go-common/library/net/http/blademaster/middleware/verify"
  14. "go-common/library/net/trace"
  15. "github.com/BurntSushi/toml"
  16. "go-common/library/database/orm"
  17. "go-common/library/net/rpc/liverpc"
  18. )
  19. var (
  20. confPath string
  21. client *conf.Client
  22. // Conf config
  23. Conf = &Config{}
  24. )
  25. // Config .
  26. type Config struct {
  27. Log *log.Config
  28. BM *bm.ServerConfig
  29. Verify *verify.Config
  30. Tracer *trace.Config
  31. Redis *redis.Config
  32. Memcache *memcache.Config
  33. MySQL *sql.Config
  34. Ecode *ecode.Config
  35. Cfg *Cfg
  36. ORM *orm.Config
  37. LiveRpc map[string]*liverpc.ClientConfig
  38. Warden *warden.ClientConfig
  39. HTTPClient *bm.ClientConfig
  40. }
  41. // Cfg def
  42. type Cfg struct {
  43. // ExpireCountFrequency crontab frequency
  44. ExpireCountFrequency string
  45. // SetExpireFrequency crontab frequency
  46. SetExpireFrequency string
  47. }
  48. func init() {
  49. flag.StringVar(&confPath, "conf", "", "default config path")
  50. }
  51. // Init init conf
  52. func Init() error {
  53. if confPath != "" {
  54. return local()
  55. }
  56. return remote()
  57. }
  58. func local() (err error) {
  59. _, err = toml.DecodeFile(confPath, &Conf)
  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. }