conf.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. package conf
  2. import (
  3. "errors"
  4. "flag"
  5. "github.com/BurntSushi/toml"
  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. bm "go-common/library/net/http/blademaster"
  12. "go-common/library/net/http/blademaster/middleware/permit"
  13. "go-common/library/net/trace"
  14. xtime "go-common/library/time"
  15. )
  16. // global var
  17. var (
  18. confPath string
  19. client *conf.Client
  20. // Conf config
  21. Conf = &Config{}
  22. )
  23. // Config config set
  24. type Config struct {
  25. Log *log.Config
  26. BM *bm.ServerConfig
  27. Tracer *trace.Config
  28. Redis *redis.Config
  29. Ecode *ecode.Config
  30. Auth *permit.Config
  31. HTTPClient *bm.ClientConfig
  32. Es *ElasticSearch
  33. DB *DB
  34. URL *URL
  35. Env string
  36. SourcePath string
  37. Bfs *Bfs
  38. }
  39. // URL search items
  40. type URL struct {
  41. ItemSearch string
  42. }
  43. // DB db config
  44. type DB struct {
  45. MallDB *sql.Config
  46. TicketDB *sql.Config
  47. }
  48. // ElasticSearch config
  49. type ElasticSearch struct {
  50. Addr []string
  51. }
  52. // Bfs config
  53. type Bfs struct {
  54. Timeout xtime.Duration
  55. MaxFileSize int
  56. Bucket string
  57. Addr string
  58. Key string
  59. Secret string
  60. }
  61. func init() {
  62. flag.StringVar(&confPath, "conf", "", "default config path")
  63. }
  64. // Init init conf
  65. func Init() error {
  66. if confPath != "" {
  67. return local()
  68. }
  69. return remote()
  70. }
  71. func local() (err error) {
  72. _, err = toml.DecodeFile(confPath, &Conf)
  73. return
  74. }
  75. func remote() (err error) {
  76. if client, err = conf.New(); err != nil {
  77. return
  78. }
  79. if err = load(); err != nil {
  80. return
  81. }
  82. go func() {
  83. for range client.Event() {
  84. log.Info("config reload")
  85. if load() != nil {
  86. log.Error("config reload error (%v)", err)
  87. }
  88. }
  89. }()
  90. return
  91. }
  92. func load() (err error) {
  93. var (
  94. s string
  95. ok bool
  96. tmpConf *Config
  97. )
  98. if s, ok = client.Toml2(); !ok {
  99. return errors.New("load config center error")
  100. }
  101. if _, err = toml.Decode(s, &tmpConf); err != nil {
  102. return errors.New("could not decode config")
  103. }
  104. *Conf = *tmpConf
  105. return
  106. }