conf.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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/verify"
  10. "go-common/library/net/rpc/warden"
  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 *HTTPGeneral
  24. Verify *verify.Config
  25. Tracer *trace.Config
  26. Ecode *ecode.Config
  27. RPC *warden.ServerConfig
  28. URL map[string]string
  29. }
  30. //HTTPGeneral .
  31. type HTTPGeneral struct {
  32. Server *bm.ServerConfig
  33. Client *bm.ClientConfig
  34. }
  35. func init() {
  36. flag.StringVar(&confPath, "conf", "", "default config path")
  37. }
  38. // Init init conf
  39. func Init() error {
  40. if confPath != "" {
  41. return local()
  42. }
  43. return remote()
  44. }
  45. func local() (err error) {
  46. _, err = toml.DecodeFile(confPath, &Conf)
  47. return
  48. }
  49. func remote() (err error) {
  50. if client, err = conf.New(); err != nil {
  51. return
  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. }