conf.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package conf
  2. import (
  3. "errors"
  4. "flag"
  5. "go-common/library/conf"
  6. "go-common/library/database/sql"
  7. "go-common/library/log"
  8. bm "go-common/library/net/http/blademaster"
  9. "github.com/BurntSushi/toml"
  10. )
  11. var (
  12. // Conf global config variable
  13. Conf = &Config{}
  14. confPath string
  15. client *conf.Client
  16. )
  17. // Config databus config struct
  18. type Config struct {
  19. // base
  20. Addr string
  21. Clusters map[string]*Kafka
  22. // Log
  23. Log *log.Config
  24. // http
  25. HTTPServer *bm.ServerConfig
  26. // mysql
  27. MySQL *sql.Config
  28. }
  29. // Kafka contains cluster, brokers, sync.
  30. type Kafka struct {
  31. Cluster string
  32. Brokers []string
  33. }
  34. func init() {
  35. flag.StringVar(&confPath, "conf", "", "config path")
  36. }
  37. //Init int config
  38. func Init() error {
  39. if confPath != "" {
  40. return local()
  41. }
  42. return remote()
  43. }
  44. func local() (err error) {
  45. _, err = toml.DecodeFile(confPath, &Conf)
  46. return
  47. }
  48. func remote() (err error) {
  49. if client, err = conf.New(); err != nil {
  50. return
  51. }
  52. if err = load(); err != nil {
  53. return
  54. }
  55. go func() {
  56. for range client.Event() {
  57. log.Info("config reload")
  58. if load() != nil {
  59. log.Error("config reload error (%v)", err)
  60. }
  61. }
  62. }()
  63. return
  64. }
  65. func load() (err error) {
  66. var (
  67. s string
  68. ok bool
  69. tmpConf *Config
  70. )
  71. if s, ok = client.Toml2(); !ok {
  72. return errors.New("load config center error")
  73. }
  74. if _, err = toml.Decode(s, &tmpConf); err != nil {
  75. return errors.New("could not decode config")
  76. }
  77. *Conf = *tmpConf
  78. return
  79. }