123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- package common
- import (
- "encoding/json"
- "fmt"
- "io"
- "log"
- "net/http"
- "sync"
- )
- type Config struct {
- Service `json:"service"`
- Mysql `json:"mysql"`
- Redis
- }
- type Service struct {
- IsDebug bool
- Httpport string
- }
- type Redis struct {
- Addr string
- Password string
- Database int
- }
- type Mysql struct {
- Host string `json:"host"`
- Database string `json:"database"`
- User string `json:"user"`
- Password string `json:"password"`
- Maxidleconns int `json:"maxidleconns"`
- Maxopenconns int `json:"max_open_conns"`
- }
- type remoteConfig struct {
- Data struct {
- Name string `json:"name"`
- EndAt string `json:"end_at"`
- Config *Config `json:"config"`
- } `json:"data"`
- Error string `json:"error"`
- }
- var c *Config
- var cOnce sync.Once
- func InitConfig() {
- rConfig := &remoteConfig{}
- usingRemote(rConfig)
- c = rConfig.Data.Config
- log.Printf("配置加载完成,当前配置 %+v", c)
- }
- func GetConfig() *Config {
- cOnce.Do(func() {
- InitConfig()
- })
- return c
- }
- func usingRemote(rConfig *remoteConfig) {
- resp, err := http.Get(fmt.Sprintf("http://kconf.kphcdr.com/api/config?appkey=%s&env=%s&password=%s", APP_KEY, Env, KCONF_PASSWORD))
- if err != nil {
- panic(fmt.Sprintf("拉取配置失败:%s", err))
- }
- defer func() {
- err := resp.Body.Close()
- if err != nil {
- panic(err)
- }
- }()
- body, err := io.ReadAll(resp.Body)
- if err != nil {
- panic(fmt.Sprintf("读取配置失败:%s", err))
- }
- if err := json.Unmarshal(body, &rConfig); err != nil {
- panic(err)
- }
- if rConfig.Error != "" {
- panic(rConfig.Error)
- }
- }
|