conf.go 1.7 KB

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