generated from pkg/go-template
feat: pkg
This commit is contained in:
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
Reference in New Issue
Block a user