-
Notifications
You must be signed in to change notification settings - Fork 0
/
grpc.go
91 lines (77 loc) · 1.73 KB
/
grpc.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
91
package grpc
import (
"context"
"crypto/tls"
"google.golang.org/grpc/credentials"
"github.com/balachandar-git/jet-config/source"
proto "github.com/balachandar-git/jet-config/source/grpc/proto"
"google.golang.org/grpc"
)
type grpcSource struct {
addr string
path string
opts source.Options
tlsConfig *tls.Config
client *grpc.ClientConn
}
var (
DefaultPath = "/micro/config"
DefaultAddress = "localhost:8080"
)
func (g *grpcSource) Read() (set *source.ChangeSet, err error) {
var opts []grpc.DialOption
// check if secure is necessary
if g.tlsConfig != nil {
opts = append(opts, grpc.WithTransportCredentials(credentials.NewTLS(g.tlsConfig)))
} else {
opts = append(opts, grpc.WithInsecure())
}
g.client, err = grpc.Dial(g.addr, opts...)
if err != nil {
return nil, err
}
cl := proto.NewSourceClient(g.client)
rsp, err := cl.Read(context.Background(), &proto.ReadRequest{
Path: g.path,
})
if err != nil {
return nil, err
}
return toChangeSet(rsp.ChangeSet), nil
}
func (g *grpcSource) Watch() (source.Watcher, error) {
cl := proto.NewSourceClient(g.client)
rsp, err := cl.Watch(context.Background(), &proto.WatchRequest{
Path: g.path,
})
if err != nil {
return nil, err
}
return newWatcher(rsp)
}
func (g *grpcSource) String() string {
return "grpc"
}
func NewSource(opts ...source.Option) source.Source {
var options source.Options
for _, o := range opts {
o(&options)
}
addr := DefaultAddress
path := DefaultPath
if options.Context != nil {
a, ok := options.Context.Value(addressKey{}).(string)
if ok {
addr = a
}
p, ok := options.Context.Value(pathKey{}).(string)
if ok {
path = p
}
}
return &grpcSource{
addr: addr,
path: path,
opts: options,
}
}