conf.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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/orm"
  8. "go-common/library/log"
  9. bm "go-common/library/net/http/blademaster"
  10. "go-common/library/net/http/blademaster/middleware/permit"
  11. "go-common/library/net/trace"
  12. "go-common/library/time"
  13. "github.com/BurntSushi/toml"
  14. )
  15. // Conf global variable.
  16. var (
  17. Conf = &Config{}
  18. confPath string
  19. client *conf.Client
  20. )
  21. // Config struct of conf.
  22. type Config struct {
  23. // log
  24. Log *log.Config
  25. // db
  26. Mysql *orm.Config
  27. // redis
  28. Redis *Redis
  29. // tracer
  30. Tracer *trace.Config
  31. // Answer
  32. Answer *Answer
  33. // bm
  34. BM *bm.ServerConfig
  35. Auth *permit.Config
  36. }
  37. // Redis .
  38. type Redis struct {
  39. *redis.Config
  40. Expire time.Duration
  41. AnsCountExpire time.Duration
  42. AnsAddFlagCountExpire time.Duration
  43. }
  44. // Answer conf.
  45. type Answer struct {
  46. Debug bool
  47. FontFilePath string
  48. }
  49. func configCenter() (err error) {
  50. if client, err = conf.New(); err != nil {
  51. panic(err)
  52. }
  53. if err = load(); err != nil {
  54. return
  55. }
  56. go func() {
  57. for range client.Event() {
  58. log.Info("config reload")
  59. if load() != nil {
  60. log.Error("config reload error (%v)", err)
  61. }
  62. }
  63. }()
  64. return
  65. }
  66. func load() (err error) {
  67. var (
  68. s string
  69. ok bool
  70. tmpConf *Config
  71. )
  72. if s, ok = client.Toml2(); !ok {
  73. return errors.New("load config center error")
  74. }
  75. if _, err = toml.Decode(s, &tmpConf); err != nil {
  76. return errors.New("could not decode config")
  77. }
  78. *Conf = *tmpConf
  79. return
  80. }
  81. func init() {
  82. flag.StringVar(&confPath, "conf", "", "default config path")
  83. }
  84. // Init create config instance.
  85. func Init() (err error) {
  86. if confPath == "" {
  87. err = configCenter()
  88. } else {
  89. _, err = toml.DecodeFile(confPath, &Conf)
  90. }
  91. return
  92. }