config.go 1.5 KB

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