2021-12-14 13:53:22 +08:00
|
|
|
package bgm
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bgm/consts"
|
|
|
|
"context"
|
|
|
|
"fmt"
|
|
|
|
ctxLogger "github.com/luizsuper/ctxLoggers"
|
|
|
|
clientv3 "go.etcd.io/etcd/client/v3"
|
|
|
|
"go.uber.org/zap"
|
|
|
|
"os"
|
|
|
|
"strings"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Config map[string]string
|
|
|
|
|
|
|
|
var (
|
|
|
|
client *clientv3.Client
|
|
|
|
configMap = make(Config, 0)
|
|
|
|
config clientv3.Config
|
|
|
|
err error
|
|
|
|
)
|
|
|
|
|
|
|
|
func GetConfig() {
|
|
|
|
env := GetEnvDefault(consts.Env, consts.Local)
|
|
|
|
host := GetEnvDefault(consts.Configs, consts.Etcd)
|
|
|
|
switch host {
|
|
|
|
case consts.Etcd:
|
|
|
|
etcdReader(env)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func etcdReader(env string) {
|
|
|
|
kv := clientv3.NewKV(client)
|
|
|
|
defer client.Close()
|
|
|
|
if getResp, err := kv.Get(context.TODO(), fmt.Sprintf("/config/%v/", env), clientv3.WithPrefix()); err == nil {
|
|
|
|
for _, v := range getResp.Kvs {
|
|
|
|
configMap[string(v.Key)] = string(v.Value)
|
|
|
|
}
|
|
|
|
} else {
|
2021-12-14 14:59:42 +08:00
|
|
|
ctxLogger.Error(nil, consts.EtcReadError, zap.String("reason", err.Error()))
|
2021-12-14 13:53:22 +08:00
|
|
|
os.Exit(-1)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func ConfigMap() Config {
|
|
|
|
return configMap
|
|
|
|
}
|
|
|
|
|
|
|
|
func GetConfigKey(key string) string {
|
|
|
|
configs := GetEnvDefault(consts.Configs, "")
|
|
|
|
env := GetEnvDefault(consts.Env, "")
|
|
|
|
switch configs {
|
|
|
|
case consts.Etcd:
|
|
|
|
return fmt.Sprintf("/config/%v/%v", env, key)
|
|
|
|
default:
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
}
|
|
|
|
func init() {
|
|
|
|
connect()
|
|
|
|
}
|
|
|
|
|
|
|
|
func connect() {
|
|
|
|
ends := []string{""}
|
|
|
|
envDefault := GetEnvDefault(consts.EtcdEnd, consts.EtcdEndDefault)
|
|
|
|
ends = strings.Split(envDefault, ",")
|
|
|
|
config = clientv3.Config{
|
|
|
|
Endpoints: ends,
|
|
|
|
DialTimeout: 5 * time.Second,
|
|
|
|
}
|
|
|
|
if client, err = clientv3.New(config); err != nil {
|
|
|
|
ctxLogger.FError(nil, consts.EtcConnError, zap.String(consts.ErrorReason, err.Error()))
|
|
|
|
os.Exit(-1)
|
|
|
|
}
|
|
|
|
}
|