conf.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. package conf
  2. import (
  3. "errors"
  4. "flag"
  5. "go-common/library/database/orm"
  6. "go-common/library/cache/memcache"
  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. "go-common/library/time"
  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
  32. MySQL *sql.Config
  33. Ecode *ecode.Config
  34. DB *DB
  35. CacheBucket int
  36. CacheCapacity int
  37. CacheTimeout int64
  38. CacheInstCnt int
  39. HttpClient *bm.ClientConfig
  40. }
  41. // Memcache struct
  42. type Memcache struct {
  43. *memcache.Config
  44. ConfKvExpire time.Duration
  45. }
  46. // DB conf.
  47. type DB struct {
  48. Resource *orm.Config
  49. ResourceReader *orm.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. }