conf.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package conf
  2. import (
  3. "errors"
  4. "flag"
  5. "go-common/library/cache/memcache"
  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/verify"
  13. "go-common/library/net/trace"
  14. "github.com/BurntSushi/toml"
  15. )
  16. var (
  17. confPath string
  18. client *conf.Client
  19. // Conf config
  20. Conf = &Config{}
  21. )
  22. // Config .
  23. type Config struct {
  24. Log *log.Config
  25. BM *bm.ServerConfig
  26. Verify *verify.Config
  27. Tracer *trace.Config
  28. Redis *redis.Config
  29. Memcache *memcache.Config
  30. MySQL *sql.Config
  31. Ecode *ecode.Config
  32. }
  33. func init() {
  34. flag.StringVar(&confPath, "conf", "", "default config path")
  35. }
  36. // Init init conf
  37. func Init() error {
  38. if confPath != "" {
  39. return local()
  40. }
  41. return remote()
  42. }
  43. func local() (err error) {
  44. _, err = toml.DecodeFile(confPath, &Conf)
  45. return
  46. }
  47. func remote() (err error) {
  48. if client, err = conf.New(); err != nil {
  49. return
  50. }
  51. if err = load(); err != nil {
  52. return
  53. }
  54. go func() {
  55. for range client.Event() {
  56. log.Info("config reload")
  57. if load() != nil {
  58. log.Error("config reload error (%v)", err)
  59. }
  60. }
  61. }()
  62. return
  63. }
  64. func load() (err error) {
  65. var (
  66. s string
  67. ok bool
  68. tmpConf *Config
  69. )
  70. if s, ok = client.Toml2(); !ok {
  71. return errors.New("load config center error")
  72. }
  73. if _, err = toml.Decode(s, &tmpConf); err != nil {
  74. return errors.New("could not decode config")
  75. }
  76. *Conf = *tmpConf
  77. return
  78. }