conf.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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. "go-common/library/queue/databus"
  10. "go-common/library/time"
  11. "github.com/BurntSushi/toml"
  12. )
  13. // global var
  14. var (
  15. ConfPath string
  16. client *conf.Client
  17. // Conf config
  18. Conf = &Config{}
  19. )
  20. // Config config set
  21. type Config struct {
  22. // base
  23. // log
  24. Log *log.Config
  25. // db
  26. DB *DB
  27. // databus
  28. UserSub *databus.Config
  29. // Env
  30. Env string
  31. // memcache
  32. Memcache *Memcache
  33. }
  34. // DB db config.
  35. type DB struct {
  36. Wallet *sql.Config
  37. }
  38. // Memcache config
  39. type Memcache struct {
  40. Wallet *memcache.Config
  41. WalletExpire time.Duration
  42. }
  43. func init() {
  44. flag.StringVar(&ConfPath, "conf", "", "default config path")
  45. }
  46. // Init init conf
  47. func Init() error {
  48. if ConfPath != "" {
  49. return local()
  50. }
  51. return remote()
  52. }
  53. func local() (err error) {
  54. _, err = toml.DecodeFile(ConfPath, &Conf)
  55. return
  56. }
  57. func remote() (err error) {
  58. if client, err = conf.New(); err != nil {
  59. return
  60. }
  61. if err = load(); err != nil {
  62. return
  63. }
  64. go func() {
  65. for range client.Event() {
  66. log.Info("config reload")
  67. if load() != nil {
  68. log.Error("config reload error (%v)", err)
  69. }
  70. }
  71. }()
  72. return
  73. }
  74. func load() (err error) {
  75. var (
  76. s string
  77. ok bool
  78. tmpConf *Config
  79. )
  80. if s, ok = client.Toml2(); !ok {
  81. return errors.New("load config center error")
  82. }
  83. if _, err = toml.Decode(s, &tmpConf); err != nil {
  84. return errors.New("could not decode config")
  85. }
  86. *Conf = *tmpConf
  87. return
  88. }