forked from actatum/stormrpc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
93 lines (78 loc) · 1.9 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
// Package stormrpc provides the functionality for creating RPC servers/clients that communicate via NATS.
package stormrpc
import (
"context"
"errors"
"github.com/nats-io/nats.go"
)
// Client represents a stormRPC client. It contains all functionality for making RPC requests
// to stormRPC servers.
type Client struct {
nc *nats.Conn
}
// NewClient returns a new instance of a Client.
func NewClient(natsURL string, _ ...ClientOption) (*Client, error) {
nc, err := nats.Connect(natsURL)
if err != nil {
return nil, err
}
return &Client{
nc: nc,
}, nil
}
type clientOptions struct{}
// ClientOption represents functional options for configuring a stormRPC Client.
type ClientOption interface {
apply(*clientOptions)
}
// Close closes the underlying nats connection.
func (c *Client) Close() {
c.nc.Close()
}
// Do completes a request to a stormRPC Server.
func (c *Client) Do(ctx context.Context, r Request, opts ...CallOption) Response {
options := callOptions{
headers: make(map[string]string),
}
for _, o := range opts {
err := o.before(&options)
if err != nil {
return NewErrorResponse("", err)
}
}
applyOptions(&r, &options)
dl, ok := ctx.Deadline()
if ok {
setDeadlineHeader(r.Header, dl)
}
msg, err := c.nc.RequestMsgWithContext(ctx, r.Msg)
if errors.Is(err, nats.ErrNoResponders) {
return Response{
Msg: msg,
Err: Errorf(ErrorCodeInternal, "no servers available for subject: %s", r.Subject()),
}
}
if err != nil {
return Response{
Msg: msg,
Err: err, // TODO: probably use errorf and inspect different error types from nats.
}
}
// Inspect headers and set error if appropriate
rpcErr := parseErrorHeader(msg.Header)
if rpcErr != nil {
return Response{
Msg: msg,
Err: rpcErr,
}
}
return Response{
Msg: msg,
Err: nil,
}
}
func applyOptions(r *Request, options *callOptions) {
for k, v := range options.headers {
r.Header.Set(k, v)
}
}