conf.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. package conf
  2. import (
  3. "flag"
  4. "errors"
  5. "github.com/BurntSushi/toml"
  6. "go-common/library/cache/memcache"
  7. "go-common/library/conf"
  8. "go-common/library/database/sql"
  9. "go-common/library/log"
  10. bm "go-common/library/net/http/blademaster"
  11. "go-common/library/net/http/blademaster/middleware/permit"
  12. xtime "go-common/library/time"
  13. )
  14. // ConfPath str.
  15. var (
  16. ConfPath string
  17. Conf = &Config{}
  18. client *conf.Client
  19. )
  20. // Config app meta config.
  21. type Config struct {
  22. // base
  23. // ELK
  24. Log *log.Config
  25. // Auth
  26. Auth *permit.Config
  27. // http
  28. BM *bm.ServerConfig
  29. // mysql
  30. Mysql *sql.Config
  31. // http client
  32. HTTPClient *bm.ClientConfig
  33. // host
  34. Host *Host
  35. // Memcache
  36. Memcache *Memcache
  37. }
  38. // Memcache conf.
  39. type Memcache struct {
  40. Laser struct {
  41. *memcache.Config
  42. Expire xtime.Duration
  43. }
  44. }
  45. // Host conf.
  46. type Host struct {
  47. Manager string
  48. }
  49. func init() {
  50. flag.StringVar(&ConfPath, "conf", "", "default config path")
  51. }
  52. // Init fn.
  53. func Init() (err error) {
  54. if ConfPath != "" {
  55. return local()
  56. }
  57. return remote()
  58. }
  59. func local() (err error) {
  60. _, err = toml.DecodeFile(ConfPath, &Conf)
  61. return
  62. }
  63. func remote() (err error) {
  64. if client, err = conf.New(); err != nil {
  65. return
  66. }
  67. if err = load(); err != nil {
  68. return
  69. }
  70. go func() {
  71. for range client.Event() {
  72. log.Info("config reload")
  73. if load() != nil {
  74. log.Error("config reload error (%v)", err)
  75. }
  76. }
  77. }()
  78. return
  79. }
  80. func load() (err error) {
  81. var (
  82. cf string
  83. ok bool
  84. tmpConf *Config
  85. )
  86. if cf, ok = client.Toml2(); !ok {
  87. return errors.New("load config center error")
  88. }
  89. if _, err = toml.Decode(cf, &tmpConf); err != nil {
  90. return errors.New("could not decode config")
  91. }
  92. *Conf = *tmpConf
  93. return
  94. }