-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
631 lines (543 loc) · 14.1 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
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
package miso
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"regexp"
"strings"
"time"
"github.com/spf13/cast"
)
const (
formEncoded = "application/x-www-form-urlencoded"
applicationJson = "application/json"
textPlain = "text/plain"
contentType = "Content-Type"
httpProto = "http://"
httpsProto = "https://"
)
var (
httpProtoRegex = regexp.MustCompile(`(?i)https?://`)
MisoDefaultClient *http.Client
)
func init() {
MisoDefaultClient = &http.Client{Timeout: 15 * time.Second}
transport := http.DefaultTransport.(*http.Transport).Clone()
transport.MaxIdleConns = 500
transport.MaxIdleConnsPerHost = 50
transport.IdleConnTimeout = time.Minute * 5
MisoDefaultClient.Transport = transport
}
// Helper type for handling HTTP responses
type TResponse struct {
Rail Rail
Ctx context.Context
Resp *http.Response
RespHeader http.Header
StatusCode int
Err error
}
// Close Response
func (tr *TResponse) Close() error {
return tr.Resp.Body.Close()
}
// Write the response data to the given writer.
//
// Response is always closed automatically.
//
// If response body is somehow empty, *miso.NoneErr is returned.
func (tr *TResponse) WriteTo(writer io.Writer) (int64, error) {
if tr.Err != nil {
return 0, tr.Err
}
if tr.Resp.Body == nil {
return 0, NoneErr
}
defer tr.Close()
return io.Copy(writer, tr.Resp.Body)
}
// Read response as []bytes.
//
// Response is always closed automatically.
//
// If response body is somehow empty, *miso.NoneErr is returned.
func (tr *TResponse) Bytes() ([]byte, error) {
if tr.Err != nil {
return nil, tr.Err
}
if tr.Resp.Body == nil {
return nil, NoneErr
}
defer tr.Close()
return io.ReadAll(tr.Resp.Body)
}
// Read response as string.
//
// Response is always closed automatically.
//
// If response body is somehow empty, *miso.NoneErr is returned.
func (tr *TResponse) Str() (string, error) {
if tr.Err != nil {
return "", tr.Err
}
if tr.Resp.Body == nil {
return "", NoneErr
}
defer tr.Close()
b, e := io.ReadAll(tr.Resp.Body)
if e != nil {
return "", e
}
return UnsafeByt2Str(b), nil
}
// Read response as JSON object.
//
// Response is always closed automatically.
//
// If response body is somehow empty, *miso.NoneErr is returned.
func (tr *TResponse) Json(ptr any) error {
if tr.Err != nil {
return tr.Err
}
if tr.Resp.Body == nil {
return NoneErr
}
defer tr.Close()
body, e := io.ReadAll(tr.Resp.Body)
if e != nil {
return e
}
if e = ParseJson(body, ptr); e != nil {
s := UnsafeByt2Str(body)
errMsg := fmt.Sprintf("Failed to unmarshal json from response, body: %v, %v", s, e)
tr.Rail.Error(errMsg)
return fmt.Errorf(errMsg)
}
return nil
}
// Is status code 2xx
func (tr *TResponse) Is2xx() bool {
return tr.StatusCode >= 200 && tr.StatusCode < 300
}
// Check if it's 2xx, else return error
func (tr *TResponse) Require2xx() error {
if !tr.Is2xx() {
var body string
byt, err := tr.Bytes()
if err == nil {
body = UnsafeByt2Str(byt)
}
return fmt.Errorf("unknown error, status code: %v, body: %v", tr.StatusCode, body)
}
return nil
}
// Helper type for sending HTTP requests
//
// Provides convenients methods to build requests, use http.Client and propagate tracing information
type TClient struct {
Url string // request url (absolute or relative)
Headers map[string][]string // request headers
Ctx context.Context // context provided by caller
QueryParam map[string][]string // query parameters
Rail Rail // rail
client *http.Client
serviceName string
trace bool
discoverService bool
require2xx bool
}
// Change the underlying *http.Client
func (t *TClient) UseClient(client *http.Client) *TClient {
t.client = client
return t
}
// Prepare request url.
//
// If service discovery is enabled, serviceName will be resolved using Consul.
//
// If consul is disabled, t.serviceName is used directly as the host name. This is especially useful in container environment.
func (t *TClient) prepReqUrl() (string, error) {
url := t.Url
if t.discoverService {
sr := GetServiceRegistry()
if sr == nil {
return "", errors.New("service discovery enabled, but no service registry available")
}
resolved, err := sr.ResolveUrl(t.Rail, t.serviceName, t.Url)
if err != nil {
t.Rail.Errorf("Resolve service address failed, service: %v, %v", t.serviceName, err)
return "", err
}
url = resolved
}
if !httpProtoRegex.MatchString(url) { // missing a protocol
url = httpProto + url
}
return concatQueryParam(url, t.QueryParam), nil
}
// Requires response to have 2xx status code, if not, the *TResponse will contain error built for this specific reason.
func (t *TClient) Require2xx() *TClient {
t.require2xx = true
return t
}
// Enable service discovery
func (t *TClient) EnableServiceDiscovery(serviceName string) *TClient {
t.serviceName = serviceName
t.discoverService = true
return t
}
// Enable tracing by putting propagation key/value pairs on http headers.
func (t *TClient) EnableTracing() *TClient {
t.trace = true
return t
}
// Set Content-Type
func (t *TClient) SetContentType(ct string) *TClient {
t.SetHeaders(contentType, ct)
return t
}
// Append 'http://' protocol.
//
// If service discovery is enabled, or the url contains http protocol already, this will be skipped.
func (t *TClient) Http() *TClient {
if t.discoverService || httpProtoRegex.MatchString(t.Url) {
return t
}
t.Url = httpProto + t.Url
return t
}
// Append 'https://' protocol.
//
// If service discovery is enabled, or the url contains http protocol already, this will be skipped.
func (t *TClient) Https() *TClient {
if t.discoverService || httpProtoRegex.MatchString(t.Url) {
return t
}
t.Url = httpsProto + t.Url
return t
}
// Send GET request
func (t *TClient) Get() *TResponse {
u, e := t.prepReqUrl()
if e != nil {
return t.errorResponse(e)
}
req, e := NewGetRequest(u)
if e != nil {
return t.errorResponse(e)
}
return t.send(req)
}
// Send POST request with urlencoded form data
func (t *TClient) PostForm(data url.Values) *TResponse {
t.SetContentType(formEncoded)
return t.Post(strings.NewReader(data.Encode()))
}
// Send POST request with JSON.
//
// Use simple types like struct instad of pointer for body.
func (t *TClient) PostJson(body any) *TResponse {
jsonBody, e := WriteJson(body)
if e != nil {
return t.errorResponse(e)
}
t.SetContentType(applicationJson)
return t.Post(bytes.NewReader(jsonBody))
}
func (t *TClient) errorResponse(e error) *TResponse {
return &TResponse{Err: e, Ctx: t.Ctx, Rail: t.Rail}
}
// Send POST request with reader to request body.
func (t *TClient) Post(body io.Reader) *TResponse {
u, e := t.prepReqUrl()
if e != nil {
return t.errorResponse(e)
}
req, e := NewPostRequest(u, body)
if e != nil {
return t.errorResponse(e)
}
return t.send(req)
}
// Send POST request with bytes.
func (t *TClient) PostBytes(body []byte) *TResponse {
return t.Post(bytes.NewReader(body))
}
// Send PUT request with JSON
func (t *TClient) PutJson(body any) *TResponse {
jsonBody, e := WriteJson(body)
if e != nil {
return t.errorResponse(e)
}
t.SetContentType(applicationJson)
return t.Put(bytes.NewReader(jsonBody))
}
// Send PUT request
func (t *TClient) Put(body io.Reader) *TResponse {
u, e := t.prepReqUrl()
if e != nil {
return t.errorResponse(e)
}
req, e := NewPutRequest(u, body)
if e != nil {
return t.errorResponse(e)
}
return t.send(req)
}
// Send PUT request with bytes.
func (t *TClient) PutBytes(body []byte) *TResponse {
return t.Put(bytes.NewReader(body))
}
// Send DELETE request
func (t *TClient) Delete() *TResponse {
u, e := t.prepReqUrl()
if e != nil {
return t.errorResponse(e)
}
req, e := NewDeleteRequest(u)
if e != nil {
return t.errorResponse(e)
}
return t.send(req)
}
// Send HEAD request
func (t *TClient) Head() *TResponse {
u, e := t.prepReqUrl()
if e != nil {
return t.errorResponse(e)
}
req, e := NewHeadRequest(u)
if e != nil {
return t.errorResponse(e)
}
return t.send(req)
}
// Send OPTIONS request
func (t *TClient) Options() *TResponse {
u, e := t.prepReqUrl()
if e != nil {
return t.errorResponse(e)
}
req, e := NewOptionsRequest(u)
if e != nil {
return t.errorResponse(e)
}
return t.send(req)
}
// Send request
func (t *TClient) send(req *http.Request) *TResponse {
if t.trace {
req = TraceRequest(t.Ctx, req)
}
AddHeaders(req, t.Headers)
if IsDebugLevel() {
loggedBody := "***"
if req.Body != nil && req.GetBody != nil {
if v, ok := t.Headers[contentType]; ok && len(v) > 0 && contentTypeLoggable(v[0]) {
if copy, err := req.GetBody(); err == nil && copy != nil {
if buf, e := io.ReadAll(copy); e == nil {
loggedBody = UnsafeByt2Str(buf)
}
}
}
}
t.Rail.Debugf("%v %v, Headers: %v, Body: %v", req.Method, req.URL, req.Header, loggedBody)
}
r, e := t.client.Do(req) // send HTTP requests
var statusCode int
var respHeaders http.Header
if e == nil && r != nil {
statusCode = r.StatusCode
respHeaders = r.Header
}
tr := &TResponse{Resp: r, Err: e, Ctx: t.Ctx, Rail: t.Rail, StatusCode: statusCode, RespHeader: respHeaders}
// check http status code
if tr.Err == nil && t.require2xx {
tr.Err = tr.Require2xx()
}
return tr
}
func contentTypeLoggable(contentType string) bool {
lct := strings.ToLower(contentType)
return lct == applicationJson || lct == textPlain
}
// Append headers, subsequent method calls doesn't override previously appended headers
func (t *TClient) AddHeaders(headers map[string]string) *TClient {
for k, v := range headers {
if t.Headers[k] == nil {
t.Headers[k] = []string{v}
} else {
t.Headers[k] = append(t.Headers[k], v)
}
}
return t
}
// Append header, subsequent method calls doesn't override previously appended headers
func (t *TClient) AddHeader(k string, v string) *TClient {
if t.Headers[k] == nil {
t.Headers[k] = []string{v}
} else {
t.Headers[k] = append(t.Headers[k], v)
}
return t
}
// Overwrite header
func (t *TClient) SetHeaders(k string, v ...string) *TClient {
t.Headers[k] = v
return t
}
// Append Query Parameters, subsequent method calls doesn't override previously appended parameters
func (t *TClient) AddQueryParams(k string, v ...string) *TClient {
for i := range v {
t.addQueryParam(k, v[i])
}
return t
}
// Append Query Parameters, subsequent method calls doesn't override previously appended parameters
func (t *TClient) addQueryParam(k string, v string) *TClient {
if t.QueryParam[k] == nil {
t.QueryParam[k] = []string{v}
} else {
t.QueryParam[k] = append(t.QueryParam[k], v)
}
return t
}
// Create new defualt TClient with EnableServiceDiscovery(), EnableTracing(), and Require2xx() turned on.
//
// The provided relUrl should be a relative url starting with '/'.
func NewDynTClient(ec Rail, relUrl string, serviceName string) *TClient {
return NewTClient(ec, relUrl).EnableServiceDiscovery(serviceName).EnableTracing().Require2xx()
}
// Create new TClient.
func NewTClient(rail Rail, url string) *TClient {
return &TClient{
Url: url, Headers: map[string][]string{}, Ctx: rail.Context(), client: MisoDefaultClient,
Rail: rail, QueryParam: map[string][]string{},
}
}
// Concatenate url and query parameters
func concatQueryParam(url string, queryParams map[string][]string) string {
qp := JoinQueryParam(queryParams)
if len(qp) > 0 && !strings.HasSuffix(url, "?") {
url = url + "?" + qp
}
return url
}
// Send GET request
func SendGet(url string, headers map[string][]string) (*http.Response, error) {
req, e := NewGetRequest(url)
if e != nil {
return nil, e
}
AddHeaders(req, headers)
return MisoDefaultClient.Do(req)
}
// Add http headers
func AddHeaders(req *http.Request, headers map[string][]string) {
for k, vs := range headers {
for _, v := range vs {
req.Header.Add(k, v)
}
}
}
// Send POST request
func PostJson(url string, json string) (*http.Response, error) {
body := bytes.NewBuffer(UnsafeStr2Byt(json))
return SendPost(url, body)
}
// Send POST request
func SendPost(url string, body io.Reader) (*http.Response, error) {
req, e := NewPostRequest(url, body)
if e != nil {
return nil, e
}
return MisoDefaultClient.Do(req)
}
// Create HEAD request
func NewHeadRequest(url string) (*http.Request, error) {
req, e := http.NewRequest(http.MethodHead, url, nil)
if e != nil {
return nil, e
}
return req, e
}
// Create OPTIONS request
func NewOptionsRequest(url string) (*http.Request, error) {
req, e := http.NewRequest(http.MethodOptions, url, nil)
if e != nil {
return nil, e
}
return req, e
}
// Create DELETE request
func NewDeleteRequest(url string) (*http.Request, error) {
req, e := http.NewRequest(http.MethodDelete, url, nil)
if e != nil {
return nil, e
}
return req, e
}
// Create PUT request
func NewPutRequest(url string, body io.Reader) (*http.Request, error) {
req, e := http.NewRequest(http.MethodPut, url, body)
if e != nil {
return nil, e
}
return req, e
}
// Create POST request
func NewPostRequest(url string, body io.Reader) (*http.Request, error) {
req, e := http.NewRequest(http.MethodPost, url, body)
if e != nil {
return nil, e
}
return req, e
}
// Create GET request
func NewGetRequest(url string) (*http.Request, error) {
req, e := http.NewRequest(http.MethodGet, url, nil)
if e != nil {
return nil, e
}
return req, e
}
// Wraper request with tracing key/value pairs on http headers
func TraceRequest(ctx context.Context, req *http.Request) *http.Request {
if ctx == nil {
return req
}
UsePropagationKeys(func(key string) {
v := ctx.Value(key)
if v != nil {
if sv := cast.ToString(v); sv != "" {
req.Header.Set(key, sv)
}
}
})
return req
}
// Join query parameters
func JoinQueryParam(queryParams map[string][]string) string {
if queryParams == nil {
return ""
}
seg := []string{}
for k, vs := range queryParams {
for i := range vs {
seg = append(seg, fmt.Sprintf("%s=%s", k, url.QueryEscape(vs[i])))
}
}
return strings.Join(seg, "&")
}
// Disable TLS certificate check.
func ClientSkipTlsSecureCheck() {
MisoDefaultClient.Transport.(*http.Transport).TLSClientConfig.InsecureSkipVerify = true
}
// Set default http client timeout
func SetDefaultTimeout(ttl time.Duration) {
MisoDefaultClient.Timeout = ttl
}