|
@@ -3,10 +3,9 @@ package common
|
|
|
import (
|
|
|
"encoding/json"
|
|
|
"fmt"
|
|
|
- "go.uber.org/zap/zapcore"
|
|
|
"io"
|
|
|
+ "log"
|
|
|
"net/http"
|
|
|
- "net/url"
|
|
|
"sync"
|
|
|
)
|
|
|
|
|
@@ -14,17 +13,11 @@ type Config struct {
|
|
|
Service `json:"service"`
|
|
|
Mysql `json:"mysql"`
|
|
|
Redis
|
|
|
- Log
|
|
|
-}
|
|
|
-type Log struct {
|
|
|
- Type string
|
|
|
- Level zapcore.Level
|
|
|
}
|
|
|
|
|
|
type Service struct {
|
|
|
- IsDebug bool
|
|
|
- Httpport string
|
|
|
- UseLogger bool
|
|
|
+ IsDebug bool
|
|
|
+ Httpport string
|
|
|
}
|
|
|
type Redis struct {
|
|
|
Addr string
|
|
@@ -40,24 +33,46 @@ type Mysql struct {
|
|
|
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() {
|
|
|
- type remoteConfig struct {
|
|
|
- Data struct {
|
|
|
- Name string `json:"name"`
|
|
|
- EndAt int `json:"end_at"`
|
|
|
- Config *Config `json:"config"`
|
|
|
- } `json:"data"`
|
|
|
- }
|
|
|
+
|
|
|
rConfig := &remoteConfig{}
|
|
|
- resp, err := http.PostForm(fmt.Sprintf("http://kconf.kphcdr.com/api/config/all?app_key=%s&env=%s", APP_KEY, Env), url.Values{})
|
|
|
+ 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 resp.Body.Close()
|
|
|
+
|
|
|
+ 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))
|
|
@@ -65,13 +80,8 @@ func InitConfig() {
|
|
|
if err := json.Unmarshal(body, &rConfig); err != nil {
|
|
|
panic(err)
|
|
|
}
|
|
|
- c = rConfig.Data.Config
|
|
|
-
|
|
|
-}
|
|
|
|
|
|
-func GetConfig() *Config {
|
|
|
- cOnce.Do(func() {
|
|
|
- InitConfig()
|
|
|
- })
|
|
|
- return c
|
|
|
+ if rConfig.Error != "" {
|
|
|
+ panic(rConfig.Error)
|
|
|
+ }
|
|
|
}
|