conf.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. package conf
  2. import (
  3. "errors"
  4. "flag"
  5. "go-common/library/cache/redis"
  6. "go-common/library/conf"
  7. "go-common/library/database/orm"
  8. "go-common/library/log"
  9. bm "go-common/library/net/http/blademaster"
  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. // http
  25. HTTPServer *bm.ServerConfig
  26. // orm
  27. ORM *ORM
  28. // redis
  29. Redis *redis.Config
  30. // http client for search
  31. HTTPSearch *bm.ClientConfig
  32. // host
  33. Host *Host
  34. // job conf
  35. Job *Job
  36. }
  37. // ORM is the orm db config for workflow
  38. type ORM struct {
  39. Write *orm.Config
  40. Read *orm.Config
  41. }
  42. // Host .
  43. type Host struct {
  44. SearchURI string
  45. MessageURI string
  46. }
  47. // Job .
  48. type Job struct {
  49. ExpireProcTick time.Duration
  50. }
  51. func init() {
  52. flag.StringVar(&confPath, "conf", "", "default config path")
  53. }
  54. // Init create config instance.
  55. func Init() (err error) {
  56. if confPath != "" {
  57. return local()
  58. }
  59. return remote()
  60. }
  61. func local() (err error) {
  62. _, err = toml.DecodeFile(confPath, &Conf)
  63. return
  64. }
  65. func remote() (err error) {
  66. if client, err = conf.New(); err != nil {
  67. return
  68. }
  69. if err = load(); err != nil {
  70. return
  71. }
  72. go func() {
  73. for range client.Event() {
  74. log.Info("config reload")
  75. if load() != nil {
  76. log.Error("config reload error (%v)", err)
  77. }
  78. }
  79. }()
  80. return
  81. }
  82. func load() (err error) {
  83. var (
  84. s string
  85. ok bool
  86. tmpConf *Config
  87. )
  88. if s, ok = client.Toml2(); !ok {
  89. return errors.New("load config center error")
  90. }
  91. if _, err = toml.Decode(s, &tmpConf); err != nil {
  92. return errors.New("could not decode config")
  93. }
  94. *Conf = *tmpConf
  95. return
  96. }