conf.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. package conf
  2. import (
  3. "errors"
  4. "flag"
  5. "go-common/library/net/http/blademaster/middleware/auth"
  6. "go-common/library/cache/redis"
  7. "go-common/library/conf"
  8. ecode "go-common/library/ecode/tip"
  9. "go-common/library/log"
  10. bm "go-common/library/net/http/blademaster"
  11. "go-common/library/net/http/blademaster/middleware/verify"
  12. "go-common/library/net/trace"
  13. "github.com/BurntSushi/toml"
  14. )
  15. var (
  16. confPath string
  17. client *conf.Client
  18. // Conf config
  19. Conf = &Config{}
  20. )
  21. // Config .
  22. type Config struct {
  23. Log *log.Config
  24. BM *bm.ServerConfig
  25. Verify *verify.Config
  26. Auth *auth.Config
  27. Tracer *trace.Config
  28. Redis *redis.Config
  29. Ecode *ecode.Config
  30. Weixin *Weixin
  31. URLs *Urls
  32. }
  33. // Weixin conf
  34. type Weixin struct {
  35. AppID string
  36. Secret string
  37. }
  38. // Urls conf
  39. type Urls struct {
  40. Weixin string
  41. Jsapi string
  42. }
  43. func init() {
  44. flag.StringVar(&confPath, "conf", "", "default config path")
  45. }
  46. // Init init conf
  47. func Init() error {
  48. if confPath != "" {
  49. return local()
  50. }
  51. return remote()
  52. }
  53. func local() (err error) {
  54. _, err = toml.DecodeFile(confPath, &Conf)
  55. return
  56. }
  57. func remote() (err error) {
  58. if client, err = conf.New(); err != nil {
  59. return
  60. }
  61. if err = load(); err != nil {
  62. return
  63. }
  64. go func() {
  65. for range client.Event() {
  66. log.Info("config reload")
  67. if load() != nil {
  68. log.Error("config reload error (%v)", err)
  69. }
  70. }
  71. }()
  72. return
  73. }
  74. func load() (err error) {
  75. var (
  76. s string
  77. ok bool
  78. tmpConf *Config
  79. )
  80. if s, ok = client.Toml2(); !ok {
  81. return errors.New("load config center error")
  82. }
  83. if _, err = toml.Decode(s, &tmpConf); err != nil {
  84. return errors.New("could not decode config")
  85. }
  86. *Conf = *tmpConf
  87. return
  88. }