conf.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. // global var
  12. var (
  13. confPath string
  14. client *conf.Client
  15. // Conf config
  16. Conf = &Config{}
  17. )
  18. // Config config set
  19. type Config struct {
  20. // base
  21. // elk
  22. Log *log.Config
  23. // http
  24. BM *bm.ServerConfig
  25. // MySQL
  26. MySQL *sql.Config
  27. // kafka cluster.
  28. Clusters map[string]*Kafka
  29. // http
  30. HTTPClient *bm.ClientConfig
  31. }
  32. // Kafka contains cluster, brokers, sync.
  33. type Kafka struct {
  34. Cluster string
  35. Brokers []string
  36. }
  37. func init() {
  38. flag.StringVar(&confPath, "conf", "", "default config path")
  39. }
  40. // Init init conf
  41. func Init() error {
  42. if confPath != "" {
  43. return local()
  44. }
  45. return remote()
  46. }
  47. func local() (err error) {
  48. _, err = toml.DecodeFile(confPath, &Conf)
  49. return
  50. }
  51. func remote() (err error) {
  52. if client, err = conf.New(); err != nil {
  53. return
  54. }
  55. if err = load(); err != nil {
  56. return
  57. }
  58. go func() {
  59. for range client.Event() {
  60. log.Info("config reload")
  61. if load() != nil {
  62. log.Error("config reload error (%v)", err)
  63. }
  64. }
  65. }()
  66. return
  67. }
  68. func load() (err error) {
  69. var (
  70. s string
  71. ok bool
  72. tmpConf *Config
  73. )
  74. if s, ok = client.Toml2(); !ok {
  75. return errors.New("load config center error")
  76. }
  77. if _, err = toml.Decode(s, &tmpConf); err != nil {
  78. return errors.New("could not decode config")
  79. }
  80. *Conf = *tmpConf
  81. return
  82. }