feat: 配置读取

This commit is contained in:
2021-12-14 13:53:22 +08:00
parent 4dfe310592
commit 28fdd5a348
8 changed files with 377 additions and 23 deletions
+76
View File
@@ -0,0 +1,76 @@
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)
}
}
+4 -3
View File
@@ -1,12 +1,13 @@
package helper
package bgm
import (
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
func GormMap() (map[string]*gorm.DB, error) {
dsn := "root:123456qwe@tcp(127.0.0.1:3306)/test?charset=utf8mb4&parseTime=True&loc=Local"
func GormMap(dsnPre string) (map[string]*gorm.DB, error) {
dsn := fmt.Sprintf("%v/test?charset=utf8mb4&parseTime=True&loc=Local", dsnPre)
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
return map[string]*gorm.DB{"local": db}, err
}
+12
View File
@@ -0,0 +1,12 @@
package bgm
import "os"
func GetEnvDefault(key, defVal string) string {
val, ex := os.LookupEnv(key)
if !ex {
os.Setenv(key, defVal)
return defVal
}
return val
}