feat: pkg

This commit is contained in:
2022-01-11 00:48:03 +08:00
parent d5714c2c3d
commit 35119f2003
11 changed files with 882 additions and 4 deletions
+51
View File
@@ -0,0 +1,51 @@
package config
import (
"encoding/json"
"fmt"
"git.icechen.cn/monorepo/backend/pkg/etcd"
"github.com/pkg/errors"
)
const (
prefix = "/config"
env = "/env"
)
const (
EnvTest = "test"
EnvOnl = "onl"
)
// GetConfig 根据etcd获取存入配置
func GetConfig(name string, config interface{}) error {
key := fmt.Sprintf("%v/config/%v", prefix, name)
value, err := etcd.GetValue(key)
if err != nil {
return err
}
err = json.Unmarshal([]byte(value), config)
if err != nil {
return errors.WithMessage(err, "etcd配置解析到json失败")
}
return nil
}
func GetMysql(name string) (string, error) {
key := fmt.Sprintf("%v/mysql/%v", prefix, name)
return etcd.GetValue(key)
}
func GetEnv() (string, error) {
return etcd.GetValue(env)
}
func IsTest() bool {
envString, _ := GetEnv()
return envString == EnvTest
}
func IsOnl() bool {
envString, _ := GetEnv()
return envString == EnvOnl
}
+36
View File
@@ -0,0 +1,36 @@
package config
import (
"fmt"
"testing"
)
type config struct {
Redis string `json:"redis,omitempty"`
Es string `json:"es,omitempty"`
}
func TestGetMysql(t *testing.T) {
//获取 /config/mysql/api-zeus 的str
mysql, err := GetMysql("api-zeus")
if err != nil {
fmt.Println(err)
}
fmt.Println(mysql)
}
func TestConfig(t *testing.T) {
c := new(config)
err := GetConfig("api-zeus", c)
if err != nil {
fmt.Println(err)
}
}
func TestEnv(t *testing.T) {
env, err := GetEnv()
if err != nil {
fmt.Println(err)
}
fmt.Println(env)
}