conf.go 1.5 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. "go-common/library/net/rpc"
  10. "github.com/BurntSushi/toml"
  11. )
  12. var (
  13. confPath string
  14. // Conf conf
  15. Conf = &Config{}
  16. configKey = "msm-service.toml"
  17. client *conf.Client
  18. )
  19. // Config config
  20. type Config struct {
  21. // Environment string
  22. Log *log.Config
  23. BM *bm.ServerConfig
  24. HTTPClient *bm.ClientConfig
  25. ConfSvr *rpc.ClientConfig
  26. Mysql *sql.Config
  27. Tree *ServiceTree
  28. }
  29. // ServiceTree ServiceTree.
  30. type ServiceTree struct {
  31. Host string
  32. PlatformID string
  33. }
  34. func init() {
  35. flag.StringVar(&confPath, "conf", "", "config file")
  36. }
  37. // Init init.
  38. func Init() (err 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 err := load(); err != 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.Value(configKey); !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. }