forked from micro/micro
-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.go
executable file
·90 lines (78 loc) · 2 KB
/
client.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package client
import (
"encoding/json"
"net/http"
proto "github.com/2637309949/micro/v3/proto/config"
"github.com/2637309949/micro/v3/service/client"
"github.com/2637309949/micro/v3/service/config"
"github.com/2637309949/micro/v3/service/context"
"github.com/2637309949/micro/v3/service/errors"
)
var (
defaultNamespace = "micro"
name = "config"
)
type srv struct {
opts config.Options
namespace string
client proto.ConfigService
}
func (m *srv) Get(path string, options ...config.Option) (config.Value, error) {
o := config.Options{}
for _, option := range options {
option(&o)
}
nullValue := config.NewJSONValue([]byte("null"))
req, err := m.client.Get(context.DefaultContext, &proto.GetRequest{
Namespace: m.namespace,
Path: path,
Options: &proto.Options{
Secret: o.Secret,
},
}, client.WithAuthToken())
if verr := errors.FromError(err); verr != nil && verr.Code == http.StatusNotFound {
return nullValue, nil
} else if err != nil {
return nullValue, err
}
return config.NewJSONValue([]byte(req.Value.Data)), nil
}
func (m *srv) Set(path string, value interface{}, options ...config.Option) error {
o := config.Options{}
for _, option := range options {
option(&o)
}
dat, _ := json.Marshal(value)
_, err := m.client.Set(context.DefaultContext, &proto.SetRequest{
Namespace: m.namespace,
Path: path,
Value: &proto.Value{
Data: string(dat),
},
Options: &proto.Options{
Secret: o.Secret,
},
}, client.WithAuthToken())
return err
}
func (m *srv) Delete(path string, options ...config.Option) error {
_, err := m.client.Delete(context.DefaultContext, &proto.DeleteRequest{
Namespace: m.namespace,
Path: path,
}, client.WithAuthToken())
return err
}
func (m *srv) String() string {
return "service"
}
func NewConfig(namespace string) *srv {
addr := name
if len(namespace) == 0 {
namespace = defaultNamespace
}
s := &srv{
namespace: namespace,
client: proto.NewConfigService(addr, client.DefaultClient),
}
return s
}