conf.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package conf
  2. import (
  3. "errors"
  4. "flag"
  5. "go-common/library/conf"
  6. "go-common/library/database/orm"
  7. ecode "go-common/library/ecode/tip"
  8. "go-common/library/log"
  9. bm "go-common/library/net/http/blademaster"
  10. "go-common/library/net/http/blademaster/middleware/permit"
  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. // identify
  24. Auth *permit.Config
  25. MySQL *orm.Config
  26. Ecode *ecode.Config
  27. HTTPClient *bm.ClientConfig
  28. }
  29. func init() {
  30. flag.StringVar(&confPath, "conf", "", "default config path")
  31. }
  32. // Init init conf
  33. func Init() error {
  34. if confPath != "" {
  35. return local()
  36. }
  37. return remote()
  38. }
  39. func local() (err error) {
  40. _, err = toml.DecodeFile(confPath, &Conf)
  41. return
  42. }
  43. func remote() (err error) {
  44. if client, err = conf.New(); err != nil {
  45. return
  46. }
  47. if err = load(); err != nil {
  48. return
  49. }
  50. go func() {
  51. for range client.Event() {
  52. log.Info("config reload")
  53. if load() != nil {
  54. log.Error("config reload error (%v)", err)
  55. }
  56. }
  57. }()
  58. return
  59. }
  60. func load() (err error) {
  61. var (
  62. s string
  63. ok bool
  64. tmpConf *Config
  65. )
  66. if s, ok = client.Toml2(); !ok {
  67. return errors.New("load config center error")
  68. }
  69. if _, err = toml.Decode(s, &tmpConf); err != nil {
  70. return errors.New("could not decode config")
  71. }
  72. *Conf = *tmpConf
  73. return
  74. }