conf.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. package conf
  2. import (
  3. "errors"
  4. "flag"
  5. "go-common/library/queue/databus"
  6. "go-common/library/net/rpc/liverpc"
  7. "go-common/library/cache/redis"
  8. "go-common/library/conf"
  9. "go-common/library/database/sql"
  10. ecode "go-common/library/ecode/tip"
  11. "go-common/library/log"
  12. bm "go-common/library/net/http/blademaster"
  13. "go-common/library/net/http/blademaster/middleware/verify"
  14. "go-common/library/net/trace"
  15. "github.com/BurntSushi/toml"
  16. )
  17. var (
  18. confPath string
  19. client *conf.Client
  20. // Conf config
  21. Conf = &Config{}
  22. )
  23. // Config .
  24. type Config struct {
  25. Log *log.Config
  26. BM *bm.ServerConfig
  27. Verify *verify.Config
  28. Tracer *trace.Config
  29. Ecode *ecode.Config
  30. Redis *Redis
  31. Database *Database
  32. LiveRpc map[string]*liverpc.ClientConfig
  33. UserReport *databus.Config
  34. RpcTimeout map[string]int64
  35. HTTPClient *bm.ClientConfig
  36. CouponConf *CouponConfig
  37. }
  38. // CouponConfig .
  39. type CouponConfig struct {
  40. Url string
  41. Coupon map[string]string
  42. }
  43. // Database database
  44. type Database struct {
  45. Lottery *sql.Config
  46. }
  47. //Redis Redis config
  48. type Redis struct {
  49. Lottery *redis.Config
  50. }
  51. func init() {
  52. flag.StringVar(&confPath, "conf", "", "default config path")
  53. }
  54. // Init init conf
  55. func Init() 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. log.Info("config reload")
  75. if load() != nil {
  76. log.Error("config reload error (%v)", 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. }
  97. // GetTimeout implementation
  98. // 获取超时
  99. func GetTimeout(k string, def int64) (timeout int64) {
  100. if t, ok := Conf.RpcTimeout[k]; ok {
  101. timeout = t
  102. } else {
  103. timeout = def
  104. }
  105. return
  106. }