conf.go 1.5 KB

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