conf.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. package conf
  2. import (
  3. "errors"
  4. "flag"
  5. "go-common/library/cache/memcache"
  6. "go-common/library/conf"
  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/verify"
  11. "go-common/library/net/trace"
  12. "github.com/BurntSushi/toml"
  13. )
  14. // Conf global var
  15. var (
  16. Conf = &Config{}
  17. confPath string
  18. client *conf.Client
  19. )
  20. // Config .
  21. type Config struct {
  22. Log *log.Config
  23. BM *bm.ServerConfig
  24. Verify *verify.Config
  25. Tracer *trace.Config
  26. Memcache *memcache.Config
  27. Ecode *ecode.Config
  28. Seo *Seo
  29. Pages []*Page
  30. Sitemaps []*Sitemap
  31. }
  32. // Seo config
  33. type Seo struct {
  34. Expire int32
  35. MaxAge int32
  36. BotList []string
  37. }
  38. // Page pro, item ...
  39. type Page struct {
  40. Name string
  41. Url string
  42. Bfs string
  43. Path string
  44. }
  45. // Sitemap app sitemap
  46. type Sitemap struct {
  47. Host string
  48. Url string
  49. }
  50. func init() {
  51. flag.StringVar(&confPath, "conf", "", "default config path")
  52. }
  53. // Init .
  54. func Init() error {
  55. if confPath != "" {
  56. return local()
  57. }
  58. return remote()
  59. }
  60. func local() (err error) {
  61. _, err = toml.DecodeFile(confPath, &Conf)
  62. return
  63. }
  64. func remote() (err error) {
  65. if client, err = conf.New(); err != nil {
  66. return
  67. }
  68. if err = load(); err != nil {
  69. return
  70. }
  71. go func() {
  72. for range client.Event() {
  73. log.Info("config reload")
  74. if load() != nil {
  75. log.Error("config reload error (%v)", err)
  76. }
  77. }
  78. }()
  79. return
  80. }
  81. func load() (err error) {
  82. var (
  83. s string
  84. ok bool
  85. tmpConf *Config
  86. )
  87. if s, ok = client.Toml2(); !ok {
  88. return errors.New("load config center error")
  89. }
  90. if _, err = toml.Decode(s, &tmpConf); err != nil {
  91. return errors.New("could not decode config")
  92. }
  93. *Conf = *tmpConf
  94. return
  95. }
  96. // GetPage get page config by name
  97. func GetPage(name string) *Page {
  98. for _, p := range Conf.Pages {
  99. if p.Name == name {
  100. return p
  101. }
  102. }
  103. return nil
  104. }
  105. // GetSitemap get sitemap url
  106. func GetSitemap(host string) *Sitemap {
  107. for _, s := range Conf.Sitemaps {
  108. if s.Host == host {
  109. return s
  110. }
  111. }
  112. return nil
  113. }