conf.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  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. "go-common/library/log"
  10. bm "go-common/library/net/http/blademaster"
  11. "go-common/library/net/trace"
  12. "go-common/library/queue/databus"
  13. "go-common/library/time"
  14. "github.com/BurntSushi/toml"
  15. )
  16. // global var
  17. var (
  18. ConfPath string
  19. client *conf.Client
  20. // Conf config
  21. Conf = &Config{}
  22. )
  23. // Config config set
  24. type Config struct {
  25. // base
  26. // elk
  27. Log *log.Config
  28. BM *HTTPServers
  29. // tracer
  30. Tracer *trace.Config
  31. // memcache
  32. Memcache *Memcache
  33. WalletExpire int32
  34. // redis
  35. Redis *Redis
  36. // db
  37. DB *DB
  38. // http client
  39. HTTPClient *bm.ClientConfig
  40. //DataBus
  41. DataBus *DataBus
  42. }
  43. type DataBus struct {
  44. Change *databus.Config
  45. }
  46. type HTTPServers struct {
  47. Inner *bm.ServerConfig
  48. Local *bm.ServerConfig
  49. }
  50. // DB db config.
  51. type DB struct {
  52. Wallet *sql.Config
  53. }
  54. type Memcache struct {
  55. Wallet *memcache.Config
  56. WalletExpire time.Duration
  57. }
  58. type Redis struct {
  59. Wallet *redis.Config
  60. }
  61. func init() {
  62. flag.StringVar(&ConfPath, "conf", "", "default config path")
  63. }
  64. // Init init conf
  65. func Init() error {
  66. if ConfPath != "" {
  67. return local()
  68. }
  69. return remote()
  70. }
  71. func local() (err error) {
  72. _, err = toml.DecodeFile(ConfPath, &Conf)
  73. return
  74. }
  75. func remote() (err error) {
  76. if client, err = conf.New(); err != nil {
  77. return
  78. }
  79. if err = load(); err != nil {
  80. return
  81. }
  82. go func() {
  83. for range client.Event() {
  84. log.Info("config reload")
  85. if load() != nil {
  86. log.Error("config reload error (%v)", err)
  87. }
  88. }
  89. }()
  90. return
  91. }
  92. func load() (err error) {
  93. var (
  94. s string
  95. ok bool
  96. tmpConf *Config
  97. )
  98. if s, ok = client.Toml(); !ok {
  99. return errors.New("load config center error")
  100. }
  101. if _, err = toml.Decode(s, &tmpConf); err != nil {
  102. return errors.New("could not decode config")
  103. }
  104. *Conf = *tmpConf
  105. return
  106. }