conf.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package conf
  2. import (
  3. "errors"
  4. "flag"
  5. "go-common/library/conf"
  6. "go-common/library/log"
  7. bm "go-common/library/net/http/blademaster"
  8. xtime "go-common/library/time"
  9. "github.com/BurntSushi/toml"
  10. )
  11. var (
  12. confPath string
  13. client *conf.Client
  14. // Conf config
  15. Conf = &Config{}
  16. )
  17. // Config .
  18. type Config struct {
  19. // log
  20. Log *log.Config
  21. BM *bm.ServerConfig
  22. Zookeepers map[string]*Zookeeper
  23. Host *Host
  24. HTTPClient *bm.ClientConfig
  25. }
  26. // Host http host
  27. type Host struct {
  28. Pitchfork string
  29. }
  30. // Zookeeper Server&Client settings.
  31. type Zookeeper struct {
  32. RackRoot string
  33. VolumeRoot string
  34. GroupRoot string
  35. PitchRoot string
  36. Addrs []string
  37. Timeout xtime.Duration
  38. }
  39. func init() {
  40. flag.StringVar(&confPath, "conf", "", "default config path")
  41. }
  42. // Init init conf
  43. func Init() error {
  44. if confPath != "" {
  45. return local()
  46. }
  47. return remote()
  48. }
  49. func local() (err error) {
  50. _, err = toml.DecodeFile(confPath, &Conf)
  51. return
  52. }
  53. func remote() (err error) {
  54. if client, err = conf.New(); err != nil {
  55. return
  56. }
  57. if err = load(); err != nil {
  58. return
  59. }
  60. go func() {
  61. for range client.Event() {
  62. log.Info("config reload")
  63. if load() != nil {
  64. log.Error("config reload error (%v)", err)
  65. }
  66. }
  67. }()
  68. return
  69. }
  70. func load() (err error) {
  71. var (
  72. s string
  73. ok bool
  74. tmpConf *Config
  75. )
  76. if s, ok = client.Toml2(); !ok {
  77. return errors.New("load config center error")
  78. }
  79. if _, err = toml.Decode(s, &tmpConf); err != nil {
  80. return errors.New("could not decode config")
  81. }
  82. *Conf = *tmpConf
  83. return
  84. }