conf.go 1.6 KB

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