conf.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package conf
  2. import (
  3. "errors"
  4. "flag"
  5. "go-common/library/conf"
  6. ecode "go-common/library/ecode/tip"
  7. "go-common/library/log"
  8. bm "go-common/library/net/http/blademaster"
  9. "go-common/library/net/http/blademaster/middleware/antispam"
  10. "go-common/library/net/http/blademaster/middleware/auth"
  11. "github.com/BurntSushi/toml"
  12. )
  13. var (
  14. confPath string
  15. client *conf.Client
  16. // Conf config
  17. Conf = &Config{}
  18. )
  19. // Config .
  20. type Config struct {
  21. Log *log.Config
  22. BM *bm.ServerConfig
  23. Auth *auth.Config
  24. Ecode *ecode.Config
  25. Antispam *antispam.Config
  26. }
  27. func init() {
  28. flag.StringVar(&confPath, "conf", "", "default config path")
  29. }
  30. // Init init conf
  31. func Init() error {
  32. if confPath != "" {
  33. return local()
  34. }
  35. return remote()
  36. }
  37. func local() (err error) {
  38. _, err = toml.DecodeFile(confPath, &Conf)
  39. return
  40. }
  41. func remote() (err error) {
  42. if client, err = conf.New(); err != nil {
  43. return
  44. }
  45. if err = load(); err != nil {
  46. return
  47. }
  48. go func() {
  49. for range client.Event() {
  50. log.Info("config reload")
  51. if load() != nil {
  52. log.Error("config reload error (%v)", err)
  53. }
  54. }
  55. }()
  56. return
  57. }
  58. func load() (err error) {
  59. var (
  60. s string
  61. ok bool
  62. tmpConf *Config
  63. )
  64. if s, ok = client.Toml2(); !ok {
  65. return errors.New("load config center error")
  66. }
  67. if _, err = toml.Decode(s, &tmpConf); err != nil {
  68. return errors.New("could not decode config")
  69. }
  70. *Conf = *tmpConf
  71. return
  72. }