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/all?app_key=%s&env=%s", APP_KEY, Env)) 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) } }