-
Notifications
You must be signed in to change notification settings - Fork 54
/
mgr.go
73 lines (63 loc) · 1.55 KB
/
mgr.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package configer
import (
"context"
"encoding/json"
tp "github.com/henrylee2cn/teleport"
"github.com/xiaoenai/tp-micro/model/etcd"
)
var mgr = struct {
etcdClient *etcd.Client
}{}
// InitMgr initializes a config manager.
func InitMgr(etcdClient *etcd.Client) {
mgr.etcdClient = etcdClient
}
// PullCtrl returns a new PULL controller.
func PullCtrl() interface{} {
return new(cfg)
}
type cfg struct {
tp.PullCtx
}
func (c *cfg) List(*struct{}) ([]string, *tp.Rerror) {
resp, err := mgr.etcdClient.Get(context.TODO(), KEY_PREFIX, etcd.WithPrefix())
if err != nil {
return nil, tp.NewRerror(100500, "Etcd Error", err.Error())
}
var r = make([]string, len(resp.Kvs))
for i, kv := range resp.Kvs {
r[i] = string(kv.Key)
}
return r, nil
}
func (c *cfg) Get(*struct{}) (string, *tp.Rerror) {
key := c.Query().Get("config-key")
resp, err := mgr.etcdClient.Get(context.TODO(), key)
if err != nil {
return "", tp.NewRerror(100500, "Etcd Error", err.Error())
}
if len(resp.Kvs) == 0 {
return "", tp.NewRerror(100404, "Not Found", "Config is not exist")
}
n := new(Node)
json.Unmarshal(resp.Kvs[0].Value, n)
if n.Config == "" {
return "{}", nil
}
return n.Config, nil
}
// ConfigKV config key-value data.
type ConfigKV struct {
Key string
Value string
}
func (c *cfg) Update(cfgKv *ConfigKV) (*struct{}, *tp.Rerror) {
_, err := mgr.etcdClient.Put(context.TODO(), cfgKv.Key, (&Node{
Initialized: true,
Config: cfgKv.Value,
}).String())
if err != nil {
return nil, tp.NewRerror(100500, "Etcd Error", err.Error())
}
return nil, nil
}