config.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package common
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "go.uber.org/zap/zapcore"
  6. "io"
  7. "net/http"
  8. "net/url"
  9. "sync"
  10. )
  11. type Config struct {
  12. Service `json:"service"`
  13. Mysql `json:"mysql"`
  14. Redis
  15. Log
  16. }
  17. type Log struct {
  18. Type string
  19. Level zapcore.Level
  20. }
  21. type Service struct {
  22. IsDebug bool
  23. Httpport string
  24. UseLogger bool
  25. }
  26. type Redis struct {
  27. Addr string
  28. Password string
  29. Database int
  30. }
  31. type Mysql struct {
  32. Host string `json:"host"`
  33. Database string `json:"database"`
  34. User string `json:"user"`
  35. Password string `json:"password"`
  36. Maxidleconns int `json:"maxidleconns"`
  37. Maxopenconns int `json:"max_open_conns"`
  38. }
  39. var c *Config
  40. var cOnce sync.Once
  41. func InitConfig() {
  42. type remoteConfig struct {
  43. Data struct {
  44. Name string `json:"name"`
  45. EndAt int `json:"end_at"`
  46. Config *Config `json:"config"`
  47. } `json:"data"`
  48. }
  49. rConfig := &remoteConfig{}
  50. resp, err := http.PostForm(fmt.Sprintf("http://kconf.kphcdr.com/api/config/all?app_key=%s&env=%s", APP_KEY, Env), url.Values{})
  51. if err != nil {
  52. panic(fmt.Sprintf("拉取配置失败:%s", err))
  53. }
  54. defer resp.Body.Close()
  55. body, err := io.ReadAll(resp.Body)
  56. if err != nil {
  57. panic(fmt.Sprintf("读取配置失败:%s", err))
  58. }
  59. if err := json.Unmarshal(body, &rConfig); err != nil {
  60. panic(err)
  61. }
  62. c = rConfig.Data.Config
  63. }
  64. func GetConfig() *Config {
  65. cOnce.Do(func() {
  66. InitConfig()
  67. })
  68. return c
  69. }