-
Notifications
You must be signed in to change notification settings - Fork 0
/
clienthttp.go
256 lines (230 loc) · 6.78 KB
/
clienthttp.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
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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
package governor
import (
"bytes"
"context"
"errors"
"io"
"net/http"
"strconv"
"strings"
"time"
"xorkevin.dev/governor/util/kjson"
"xorkevin.dev/kerrors"
"xorkevin.dev/klog"
)
type (
HTTPClient interface {
Req(method, path string, body io.Reader) (*http.Request, error)
Do(ctx context.Context, r *http.Request) (*http.Response, error)
Subclient(path string) HTTPClient
NetClient() *http.Client
}
httpClient struct {
httpc *http.Client
base string
}
configHTTPClient struct {
baseurl string
timeout time.Duration
transport http.RoundTripper
}
)
// Client http errors
var (
// ErrInvalidClientReq is returned when failing to construct the client request
ErrInvalidClientReq errInvalidClientReq
// ErrSendClientReq is returned when failing to send the client request
ErrSendClientReq errSendClientReq
// ErrInvalidServerRes is returned on an invalid server response
ErrInvalidServerRes errInvalidServerRes
)
type (
errInvalidClientReq struct{}
errSendClientReq struct{}
errInvalidServerRes struct{}
errServerRes struct{}
)
func (e errInvalidClientReq) Error() string {
return "Invalid client request"
}
func (e errSendClientReq) Error() string {
return "Failed sending client request"
}
func (e errInvalidServerRes) Error() string {
return "Invalid server response"
}
type (
// ErrorServerRes is a returned server error
ErrorServerRes struct {
Status int
Code string
Message string
}
)
// WriteError implements [xorkevin.dev/kerrors.ErrorWriter]
func (e *ErrorServerRes) WriteError(b io.Writer) {
io.WriteString(b, "(")
io.WriteString(b, strconv.Itoa(e.Status))
io.WriteString(b, ") ")
io.WriteString(b, e.Message)
if e.Code != "" {
io.WriteString(b, " [")
io.WriteString(b, e.Code)
io.WriteString(b, "]")
}
}
// Error implements error
func (e *ErrorServerRes) Error() string {
var b strings.Builder
e.WriteError(&b)
return b.String()
}
func newHTTPClient(c configHTTPClient) *httpClient {
return &httpClient{
httpc: &http.Client{
Transport: c.transport,
Timeout: c.timeout,
},
base: c.baseurl,
}
}
func (c *httpClient) Subclient(path string) HTTPClient {
return &httpClient{
httpc: c.httpc,
base: c.base + path,
}
}
// Req creates a new request
func (c *httpClient) Req(method, path string, body io.Reader) (*http.Request, error) {
req, err := http.NewRequest(method, c.base+path, body)
if err != nil {
return nil, kerrors.WithKind(err, ErrInvalidClientReq, "Malformed request")
}
return req, nil
}
// Do sends a request to the server and returns its response
func (c *httpClient) Do(ctx context.Context, r *http.Request) (_ *http.Response, retErr error) {
ctx = klog.CtxWithAttrs(ctx, klog.AString("gov.httpc.url", r.URL.String()))
res, err := c.httpc.Do(r.WithContext(ctx))
if err != nil {
return nil, kerrors.WithKind(err, ErrSendClientReq, "Failed request")
}
if res.StatusCode >= http.StatusBadRequest {
defer func() {
if err := res.Body.Close(); err != nil {
retErr = errors.Join(retErr, kerrors.WithMsg(err, "Failed to close http response body"))
}
}()
defer func() {
if _, err := io.Copy(io.Discard, res.Body); err != nil {
retErr = errors.Join(retErr, kerrors.WithMsg(err, "Failed to discard http response body"))
}
}()
b, err := io.ReadAll(res.Body)
if err != nil {
return res, kerrors.WithKind(err, ErrInvalidServerRes, "Failed reading response")
}
var errres ErrorRes
if err := kjson.Unmarshal(b, &errres); err != nil {
return res, kerrors.WithKind(err, ErrInvalidServerRes, "Failed reading response")
}
return res, kerrors.WithKind(nil, &ErrorServerRes{
Status: res.StatusCode,
Code: errres.Code,
Message: errres.Message,
}, errres.Message)
}
return res, nil
}
func (c *httpClient) NetClient() *http.Client {
return c.httpc
}
type (
// HTTPFetcher provides convenience HTTP client functionality
HTTPFetcher struct {
HTTPClient HTTPClient
}
)
// NewHTTPFetcher creates a new [*HTTPFetcher]
func NewHTTPFetcher(c HTTPClient) *HTTPFetcher {
return &HTTPFetcher{
HTTPClient: c,
}
}
// ReqJSON creates a new json request
func (c *HTTPFetcher) ReqJSON(method, path string, data interface{}) (*http.Request, error) {
b, err := kjson.Marshal(data)
if err != nil {
return nil, kerrors.WithKind(err, ErrInvalidClientReq, "Failed to encode body to json")
}
body := bytes.NewReader(b)
req, err := c.HTTPClient.Req(method, path, body)
if err != nil {
return nil, err
}
req.Header.Set(headerContentType, "application/json")
return req, nil
}
// DoNoContent sends a request to the server and discards the response body
func (c *HTTPFetcher) DoNoContent(ctx context.Context, r *http.Request) (_ *http.Response, retErr error) {
ctx = klog.CtxWithAttrs(ctx, klog.AString("gov.httpc.url", r.URL.String()))
res, err := c.HTTPClient.Do(ctx, r)
if err != nil {
return res, err
}
defer func() {
if err := res.Body.Close(); err != nil {
retErr = errors.Join(retErr, kerrors.WithMsg(err, "Failed to close http response body"))
}
}()
defer func() {
if _, err := io.Copy(io.Discard, res.Body); err != nil {
retErr = errors.Join(retErr, kerrors.WithMsg(err, "Failed to discard http response body"))
}
}()
return res, nil
}
// DoBytes sends a request to the server and gets response bytes
func (c *HTTPFetcher) DoBytes(ctx context.Context, r *http.Request) (_ *http.Response, _ []byte, retErr error) {
ctx = klog.CtxWithAttrs(ctx, klog.AString("gov.httpc.url", r.URL.String()))
res, err := c.HTTPClient.Do(ctx, r)
if err != nil {
return res, nil, err
}
defer func() {
if err := res.Body.Close(); err != nil {
retErr = errors.Join(retErr, kerrors.WithMsg(err, "Failed to close http response body"))
}
}()
defer func() {
if _, err := io.Copy(io.Discard, res.Body); err != nil {
retErr = errors.Join(retErr, kerrors.WithMsg(err, "Failed to discard http response body"))
}
}()
body, err := io.ReadAll(res.Body)
if err != nil {
return res, nil, kerrors.WithKind(err, ErrInvalidServerRes, "Failed reading response")
}
return res, body, nil
}
// DoJSON sends a request to the server and decodes response json
func (c *HTTPFetcher) DoJSON(ctx context.Context, r *http.Request, response interface{}) (_ *http.Response, retErr error) {
ctx = klog.CtxWithAttrs(ctx, klog.AString("gov.httpc.url", r.URL.String()))
res, body, err := c.DoBytes(ctx, r)
if err != nil {
return res, err
}
if !isStatusDecodable(res.StatusCode) {
return res, kerrors.WithKind(nil, ErrInvalidServerRes, "Non-decodable response")
}
if response == nil {
response = &struct{}{}
}
if err := kjson.Unmarshal(body, response); err != nil {
return res, kerrors.WithKind(err, ErrInvalidServerRes, "Failed decoding response")
}
return res, nil
}
func isStatusDecodable(status int) bool {
return status >= http.StatusOK && status < http.StatusMultipleChoices && status != http.StatusNoContent
}