backend/pkg/config/config.go

74 lines
1.5 KiB
Go
Raw Normal View History

2022-01-11 00:48:03 +08:00
package config
import (
"encoding/json"
"fmt"
2022-01-11 04:00:39 +08:00
"git.icechen.cn/monorepo/backend/pkg/env"
2022-01-11 00:48:03 +08:00
"git.icechen.cn/monorepo/backend/pkg/etcd"
"github.com/pkg/errors"
2022-01-11 04:00:39 +08:00
"reflect"
2022-01-11 00:48:03 +08:00
)
const (
prefix = "/config"
2022-01-11 04:00:39 +08:00
envKey = "/env"
2022-01-11 00:48:03 +08:00
)
2022-01-11 04:00:39 +08:00
type Env string
2022-01-11 00:48:03 +08:00
const (
2022-01-11 04:00:39 +08:00
EnvTest Env = "test"
EnvOnl Env = "onl"
2022-01-11 00:48:03 +08:00
)
// GetConfig 根据etcd获取存入配置
2022-01-11 04:00:39 +08:00
func GetConfig(config interface{}) error {
return Bind("config", config)
}
// GetMysql 获取数据库连接字符串
func GetMysql() (string, error) {
return GetString("mysql")
}
// Bind 读取配置项到结构体
func Bind(item string, out interface{}) error {
if reflect.TypeOf(out).Kind() != reflect.Ptr {
return errors.New("bind对象不是指针类型")
}
key := fmt.Sprintf("%s/%s/%s/%s", prefix, env.Namespace, env.GetAppNameWithType(), item)
2022-01-11 00:48:03 +08:00
value, err := etcd.GetValue(key)
if err != nil {
return err
}
2022-01-11 04:00:39 +08:00
err = json.Unmarshal([]byte(value), out)
2022-01-11 00:48:03 +08:00
if err != nil {
return errors.WithMessage(err, "etcd配置解析到json失败")
}
return nil
}
2022-01-11 04:00:39 +08:00
// GetString 读取配置项字符串
func GetString(item string) (string, error) {
key := fmt.Sprintf("%s/%s/%s/%s", prefix, env.Namespace, env.GetAppNameWithType(), item)
2022-01-11 00:48:03 +08:00
return etcd.GetValue(key)
}
2022-01-11 04:00:39 +08:00
// GetEnv 获取环境
func GetEnv() (Env, error) {
envString, err := etcd.GetValue(envKey)
return Env(envString), err
2022-01-11 00:48:03 +08:00
}
2022-01-11 04:00:39 +08:00
// IsTest 是否是测试环境
2022-01-11 00:48:03 +08:00
func IsTest() bool {
envString, _ := GetEnv()
return envString == EnvTest
}
2022-01-11 04:00:39 +08:00
// IsOnl 是否是正式环境
2022-01-11 00:48:03 +08:00
func IsOnl() bool {
envString, _ := GetEnv()
return envString == EnvOnl
}