conf.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. package conf
  2. import (
  3. "errors"
  4. "flag"
  5. "go-common/library/cache/memcache"
  6. "go-common/library/conf"
  7. xlog "go-common/library/log"
  8. bm "go-common/library/net/http/blademaster"
  9. "go-common/library/net/http/blademaster/middleware/auth"
  10. "go-common/library/net/rpc"
  11. "go-common/library/net/trace"
  12. xtime "go-common/library/time"
  13. "github.com/BurntSushi/toml"
  14. )
  15. // Config .
  16. type Config struct {
  17. // Env
  18. Env string
  19. // App
  20. App *bm.App
  21. // Xlog is go-common log.
  22. Xlog *xlog.Config
  23. // rpc
  24. FeedRPC *rpc.ClientConfig
  25. AccountRPC *rpc.ClientConfig
  26. // multihttp
  27. BM *bm.ServerConfig
  28. Auth *auth.Config
  29. // tracer
  30. Tracer *trace.Config
  31. // feed
  32. Feed *feed
  33. // memcache
  34. Memcache *mc
  35. }
  36. // Feed feed controls
  37. type feed struct {
  38. DefaultSize int
  39. MaxSize int
  40. }
  41. type mc struct {
  42. *memcache.Config
  43. FeedExpire xtime.Duration
  44. }
  45. var (
  46. confPath string
  47. client *conf.Client
  48. // Conf config
  49. Conf = &Config{}
  50. )
  51. func init() {
  52. flag.StringVar(&confPath, "conf", "", "config path")
  53. }
  54. // Init .
  55. func Init() (err error) {
  56. if confPath != "" {
  57. return local()
  58. }
  59. return remote()
  60. }
  61. func local() (err error) {
  62. _, err = toml.DecodeFile(confPath, &Conf)
  63. return
  64. }
  65. func remote() (err error) {
  66. if client, err = conf.New(); err != nil {
  67. return
  68. }
  69. if err = load(); err != nil {
  70. return
  71. }
  72. go func() {
  73. for range client.Event() {
  74. xlog.Info("config reload")
  75. if load() != nil {
  76. xlog.Error("config reload err")
  77. }
  78. }
  79. }()
  80. return
  81. }
  82. func load() (err error) {
  83. var (
  84. s string
  85. ok bool
  86. tmpConf *Config
  87. )
  88. if s, ok = client.Toml2(); !ok {
  89. return errors.New("load config center error")
  90. }
  91. if _, err = toml.Decode(s, &tmpConf); err != nil {
  92. return errors.New("could not decode config")
  93. }
  94. *Conf = *tmpConf
  95. return
  96. }