-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathclient.go
129 lines (106 loc) · 2.41 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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
package radiant
import (
"context"
"net/url"
"time"
api "github.com/stellarproject/radiant/api/v1"
"google.golang.org/grpc"
)
var (
defaultTimeout = time.Second * 30
)
type Client struct {
conn *grpc.ClientConn
proxyService api.ProxyClient
}
func NewClient(addr string) (*Client, error) {
grpcAddr, err := getGRPCAddr(addr)
if err != nil {
return nil, err
}
ctx, cancel := context.WithTimeout(context.Background(), defaultTimeout)
defer cancel()
c, err := grpc.DialContext(ctx,
grpcAddr,
grpc.WithInsecure(),
grpc.WithWaitForHandshake(),
)
if err != nil {
return nil, err
}
proxyService := api.NewProxyClient(c)
return &Client{
conn: c,
proxyService: proxyService,
}, nil
}
func (c *Client) AddServer(host string, opts ...AddOpts) error {
ctx, cancel := context.WithTimeout(context.Background(), defaultTimeout)
defer cancel()
srv := &api.Server{
Host: host,
Path: "/",
}
for _, o := range opts {
if err := o(ctx, srv); err != nil {
return err
}
}
if _, err := c.proxyService.AddServer(ctx, &api.AddServerRequest{
Server: srv,
}); err != nil {
return err
}
return nil
}
func (c *Client) RemoveServer(host string) error {
ctx, cancel := context.WithTimeout(context.Background(), defaultTimeout)
defer cancel()
if _, err := c.proxyService.RemoveServer(ctx, &api.RemoveServerRequest{
Host: host,
}); err != nil {
return err
}
return nil
}
func (c *Client) Servers() ([]*api.Server, error) {
ctx, cancel := context.WithTimeout(context.Background(), defaultTimeout)
defer cancel()
resp, err := c.proxyService.Servers(ctx, &api.ServersRequest{})
if err != nil {
return nil, err
}
return resp.Servers, nil
}
func (c *Client) Reload() error {
ctx, cancel := context.WithTimeout(context.Background(), defaultTimeout)
defer cancel()
if _, err := c.proxyService.Reload(ctx, &api.ReloadRequest{}); err != nil {
return err
}
return nil
}
func (c *Client) Config() ([]byte, error) {
ctx, cancel := context.WithTimeout(context.Background(), defaultTimeout)
defer cancel()
resp, err := c.proxyService.Config(ctx, &api.ConfigRequest{})
if err != nil {
return nil, err
}
return resp.Data, nil
}
func (c *Client) Close() {
c.conn.Close()
}
func getGRPCAddr(uri string) (string, error) {
u, err := url.Parse(uri)
if err != nil {
return "", err
}
switch u.Scheme {
case "unix":
return "passthrough:///" + uri, nil
default:
return u.Host, nil
}
}