conf.go 1.7 KB

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