77 lines
1.5 KiB
Go
77 lines
1.5 KiB
Go
|
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 {
|
||
|
ctxLogger.Error(nil, "etcdReaderErr", zap.String("reason", err.Error()))
|
||
|
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)
|
||
|
}
|
||
|
}
|