conf.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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/trace"
  10. "github.com/BurntSushi/toml"
  11. )
  12. var (
  13. // ConfPath local config path
  14. confPath string
  15. client *conf.Client
  16. // Conf is global config object.
  17. Conf = &Config{}
  18. )
  19. // Config is project all config
  20. type Config struct {
  21. // log
  22. Log *log.Config
  23. // Mysql
  24. MySQL *MySQL
  25. // tracer
  26. Tracer *trace.Config
  27. // http client
  28. HTTPClient *bm.ClientConfig
  29. // bm
  30. BM *bm.ServerConfig
  31. // concurrent
  32. Con *Concurrent
  33. }
  34. // MySQL mysql config
  35. type MySQL struct {
  36. Rating *sql.Config
  37. }
  38. // Concurrent concurrent compute
  39. type Concurrent struct {
  40. Concurrent int
  41. Limit int
  42. }
  43. // MailAddr mail send addr.
  44. type MailAddr struct {
  45. Type int
  46. Addr []string
  47. }
  48. func init() {
  49. flag.StringVar(&confPath, "conf", "", "default config path")
  50. }
  51. // Init init config.
  52. func Init() (err error) {
  53. if confPath != "" {
  54. _, err = toml.DecodeFile(confPath, &Conf)
  55. return
  56. }
  57. err = remote()
  58. return
  59. }
  60. func remote() (err error) {
  61. if client, err = conf.New(); err != nil {
  62. return
  63. }
  64. if err = load(); err != nil {
  65. return
  66. }
  67. go func() {
  68. for range client.Event() {
  69. log.Info("config reload")
  70. if load() != nil {
  71. log.Error("config reload error (%v)", err)
  72. }
  73. }
  74. }()
  75. return
  76. }
  77. func load() (err error) {
  78. var (
  79. s string
  80. ok bool
  81. tmpConf *Config
  82. )
  83. if s, ok = client.Toml2(); !ok {
  84. return errors.New("load config center error")
  85. }
  86. if _, err = toml.Decode(s, &tmpConf); err != nil {
  87. return errors.New("could not decode config")
  88. }
  89. *Conf = *tmpConf
  90. return
  91. }