conf.go 1.5 KB

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