-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathclient.go
More file actions
161 lines (135 loc) · 4.36 KB
/
client.go
File metadata and controls
161 lines (135 loc) · 4.36 KB
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
package gotsrpc
import (
"bytes"
"context"
"io"
"net/http"
"github.com/pkg/errors"
)
const (
HeaderServiceToService = "X-Foomo-S2s"
)
// ClientTransport to use for calls
// var ClientTransport = &http.Transport{}
var _ Client = &bufferedClient{}
type Client interface {
Call(ctx context.Context, url string, endpoint string, method string, args []interface{}, reply []interface{}) (err error)
SetClientEncoding(encoding ClientEncoding)
SetTransportHttpClient(client *http.Client)
SetDefaultHeaders(headers http.Header)
}
func NewClient() Client {
return &bufferedClient{client: defaultHttpFactory(), handle: getHandleForEncoding(EncodingMsgpack), headers: nil}
}
func NewClientWithHttpClient(client *http.Client) Client { //nolint:staticcheck
if client != nil {
return &bufferedClient{client: client, handle: getHandleForEncoding(EncodingMsgpack), headers: nil}
} else {
return &bufferedClient{client: defaultHttpFactory(), handle: getHandleForEncoding(EncodingMsgpack), headers: nil}
}
}
func newRequest(ctx context.Context, url string, contentType string, buffer *bytes.Buffer, headers http.Header) (r *http.Request, err error) {
if buffer == nil {
buffer = &bytes.Buffer{}
}
request, errRequest := http.NewRequestWithContext(ctx, http.MethodPost, url, buffer)
if errRequest != nil {
return nil, errors.Wrap(errRequest, "could not create a request")
}
if len(headers) > 0 {
request.Header = headers
}
request.Header.Set("Content-Type", contentType)
request.Header.Set("Accept", contentType)
request.Header.Set(HeaderServiceToService, "true")
return request, nil
}
type bufferedClient struct {
client *http.Client
handle *clientHandle
headers http.Header
}
func (c *bufferedClient) SetDefaultHeaders(headers http.Header) {
c.headers = headers
}
func (c *bufferedClient) SetClientEncoding(encoding ClientEncoding) {
c.handle = getHandleForEncoding(encoding)
}
func (c *bufferedClient) SetTransportHttpClient(client *http.Client) { //nolint:staticcheck
c.client = client
}
// Call calls a method on the remote service
func (c *bufferedClient) Call(ctx context.Context, url string, endpoint string, method string, args []any, reply []any) error {
var errorIndices []int
for i, v := range reply {
if isErrorPtr(v) {
errorIndices = append(errorIndices, i)
}
}
// Marshal args
var b *bytes.Buffer
if len(args) > 0 {
b = getBuffer()
defer putBuffer(b)
enc := c.handle.getEncoder(b)
err := enc.Encode(args)
c.handle.putEncoder(enc)
if err != nil {
return NewClientError(errors.Wrap(err, "failed to encode arguments"))
}
}
// Create post url
postURL := url + endpoint + "/" + method
// Create request
var headers http.Header
if c.headers != nil {
headers = c.headers.Clone()
}
request, errRequest := newRequest(ctx, postURL, c.handle.contentType, b, headers)
if errRequest != nil {
return NewClientError(errors.Wrap(errRequest, "failed to create request"))
}
resp, errDo := c.client.Do(request) //nolint:gosec // G704 - URL is constructed from trusted service configuration, not user input
if errDo != nil {
return NewClientError(errors.Wrap(errDo, "failed to send request"))
}
defer resp.Body.Close()
buf := getBuffer()
defer putBuffer(buf)
if _, err := io.Copy(buf, resp.Body); err != nil {
return NewClientError(errors.Wrap(err, "failed to read response body"))
}
// Check status
if resp.StatusCode != http.StatusOK {
return NewClientError(NewHTTPError(buf.String(), resp.StatusCode))
}
clientHandle := c.handle
if ct := resp.Header.Get("Content-Type"); ct != "" && ct != c.handle.contentType {
clientHandle = getHandlerForContentType(ct)
}
wrappedReply := reply
if clientHandle.beforeDecodeReply != nil {
if value, err := clientHandle.beforeDecodeReply(reply, errorIndices); err != nil {
return NewClientError(errors.Wrap(err, "failed to call beforeDecodeReply hook"))
} else {
wrappedReply = value
}
}
dec := clientHandle.getDecoder(buf)
err := dec.Decode(wrappedReply)
clientHandle.putDecoder(dec)
if err != nil {
return NewClientError(errors.Wrap(err, "failed to decode response"))
}
// replace error
if clientHandle.afterDecodeReply != nil {
if err := clientHandle.afterDecodeReply(&reply, wrappedReply, errorIndices); err != nil {
return NewClientError(errors.Wrap(err, "failed to call afterDecodeReply hook"))
}
}
return nil
}
func isErrorPtr(v any) bool {
_, ok := v.(*error)
return ok
}