conf.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. package conf
  2. import (
  3. "errors"
  4. "flag"
  5. "go-common/library/cache/memcache"
  6. "go-common/library/conf"
  7. "go-common/library/database/sql"
  8. "go-common/library/log"
  9. "go-common/library/queue/databus"
  10. "go-common/library/time"
  11. "github.com/BurntSushi/toml"
  12. )
  13. // Conf global variable.
  14. var (
  15. Conf = &Config{}
  16. client *conf.Client
  17. confPath string
  18. )
  19. // Config struct of conf.
  20. type Config struct {
  21. // base
  22. // log
  23. Log *log.Config
  24. // db
  25. DB *DB
  26. // mc
  27. Memcache *Memcache
  28. LevelExpire int32
  29. // databus
  30. ExpSub *databus.Config
  31. // Env
  32. Env string
  33. }
  34. // DB db config.
  35. type DB struct {
  36. Exp *sql.Config
  37. }
  38. // Memcache config
  39. type Memcache struct {
  40. Exp *memcache.Config
  41. ExpExpire time.Duration
  42. }
  43. func local() (err error) {
  44. _, err = toml.DecodeFile(confPath, &Conf)
  45. return
  46. }
  47. func remote() (err error) {
  48. if client, err = conf.New(); err != nil {
  49. return
  50. }
  51. if err = load(); err != nil {
  52. return
  53. }
  54. go func() {
  55. for range client.Event() {
  56. log.Info("config event")
  57. }
  58. }()
  59. return
  60. }
  61. func load() (err error) {
  62. var (
  63. s string
  64. ok bool
  65. tmpConf *Config
  66. )
  67. if s, ok = client.Toml2(); !ok {
  68. return errors.New("load config center error")
  69. }
  70. if _, err = toml.Decode(s, &tmpConf); err != nil {
  71. return errors.New("could not decode config")
  72. }
  73. *Conf = *tmpConf
  74. return
  75. }
  76. func init() {
  77. flag.StringVar(&confPath, "conf", "", "default config path")
  78. }
  79. // Init int config
  80. func Init() error {
  81. if confPath != "" {
  82. return local()
  83. }
  84. return remote()
  85. }