conf.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. package conf
  2. import (
  3. "errors"
  4. "flag"
  5. "go-common/library/conf"
  6. "go-common/library/database/sql"
  7. "go-common/library/log"
  8. bm "go-common/library/net/http/blademaster"
  9. "go-common/library/time"
  10. "github.com/BurntSushi/toml"
  11. )
  12. // Conf global variable.
  13. var (
  14. Conf = &Config{}
  15. client *conf.Client
  16. confPath string
  17. )
  18. // Config struct of conf.
  19. type Config struct {
  20. // base
  21. // app
  22. App *bm.App
  23. // Env
  24. Env string
  25. // goroutine sleep
  26. Tick time.Duration
  27. // log
  28. Xlog *log.Config
  29. // httpClinet
  30. Mysql *sql.Config
  31. Judge *Judge
  32. // bm service
  33. BM *bm.ServerConfig
  34. }
  35. // Judge is judge config.
  36. type Judge struct {
  37. ReservedTime time.Duration // 结案前N分钟停止获取case
  38. VoteTimer time.Duration
  39. CaseTimer time.Duration
  40. JuryTimer time.Duration
  41. ConfTimer time.Duration
  42. CaseEndVoteTotal int64
  43. }
  44. func init() {
  45. flag.StringVar(&confPath, "conf", "", "default config path")
  46. }
  47. // Init create config instance.
  48. func Init() (err error) {
  49. if confPath != "" {
  50. return local()
  51. }
  52. return remote()
  53. }
  54. func local() (err error) {
  55. _, err = toml.DecodeFile(confPath, &Conf)
  56. return
  57. }
  58. func remote() (err error) {
  59. if client, err = conf.New(); err != nil {
  60. return
  61. }
  62. if err = load(); err != nil {
  63. return
  64. }
  65. go func() {
  66. for range client.Event() {
  67. log.Info("config reload")
  68. if load() != nil {
  69. log.Error("config reload error (%v)", err)
  70. }
  71. }
  72. }()
  73. return
  74. }
  75. func load() (err error) {
  76. var (
  77. s string
  78. ok bool
  79. tmpConf *Config
  80. )
  81. if s, ok = client.Toml2(); !ok {
  82. return errors.New("load config center error")
  83. }
  84. if _, err = toml.Decode(s, &tmpConf); err != nil {
  85. return errors.New("could not decode config")
  86. }
  87. *Conf = *tmpConf
  88. return
  89. }