conf.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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. bm "go-common/library/net/http/blademaster"
  10. "go-common/library/net/rpc"
  11. "go-common/library/net/rpc/warden"
  12. "go-common/library/net/trace"
  13. "go-common/library/time"
  14. "github.com/BurntSushi/toml"
  15. )
  16. var (
  17. confPath string
  18. client *conf.Client
  19. // Conf config
  20. Conf = &Config{}
  21. )
  22. // Config .
  23. type Config struct {
  24. Log *log.Config
  25. BM *bm.ServerConfig
  26. Tracer *trace.Config
  27. Memcache *Memcache
  28. MySQL *sql.Config
  29. RPCClient2 *RPC
  30. // grpc server
  31. WardenServer *warden.ServerConfig
  32. }
  33. // RPC config
  34. type RPC struct {
  35. Vip *rpc.ClientConfig
  36. }
  37. // Memcache config
  38. type Memcache struct {
  39. *memcache.Config
  40. CardExpire time.Duration
  41. }
  42. func init() {
  43. flag.StringVar(&confPath, "conf", "", "default config path")
  44. }
  45. // Init init conf
  46. func Init() error {
  47. if confPath != "" {
  48. return local()
  49. }
  50. return remote()
  51. }
  52. func local() (err error) {
  53. _, err = toml.DecodeFile(confPath, &Conf)
  54. return
  55. }
  56. func remote() (err error) {
  57. if client, err = conf.New(); err != nil {
  58. return
  59. }
  60. if err = load(); err != nil {
  61. return
  62. }
  63. go func() {
  64. for range client.Event() {
  65. log.Info("config reload")
  66. if load() != nil {
  67. log.Error("config reload error (%v)", err)
  68. }
  69. }
  70. }()
  71. return
  72. }
  73. func load() (err error) {
  74. var (
  75. s string
  76. ok bool
  77. tmpConf *Config
  78. )
  79. if s, ok = client.Toml2(); !ok {
  80. return errors.New("load config center error")
  81. }
  82. if _, err = toml.Decode(s, &tmpConf); err != nil {
  83. return errors.New("could not decode config")
  84. }
  85. *Conf = *tmpConf
  86. return
  87. }