This repository was archived by the owner on Jul 15, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrequest.go
More file actions
465 lines (398 loc) · 9.86 KB
/
Copy pathrequest.go
File metadata and controls
465 lines (398 loc) · 9.86 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
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
package restc
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"reflect"
"strings"
"time"
"github.com/bitly/go-simplejson"
"github.com/gorilla/websocket"
"github.com/pkg/errors"
"github.com/spf13/cast"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
)
var (
DefaultCodeField = "code"
DefaultDataField = "data"
DefaultMessageField = "msg"
)
// Request allows for building up a request to a server in a chained fashion.
// Any errors are stored until the end of your call, so you only have to
// check once.
type Request struct {
c *client
verb string
path string
queryParams []QueryParam
// output
err error
// headers
headers http.Header
// body
body io.Reader
}
func NewRequest(c *client) *Request {
r := &Request{
c: c,
headers: c.headers.Clone(),
}
return r
}
func (r *Request) Verb(verb string) *Request {
r.verb = verb
return r
}
func (r *Request) GetBody() io.Reader {
return r.body
}
func (r *Request) GetParams() []QueryParam {
return r.queryParams
}
func (r *Request) parseParam() string {
if len(r.queryParams) == 0 {
return ""
}
var queryParams strings.Builder
queryParams.WriteString("?")
for i, v := range r.queryParams {
val := reflect.ValueOf(v.Value)
kind := val.Kind()
if kind == reflect.Slice || kind == reflect.Array {
length := val.Len()
for j := 0; j < length; j++ {
value := val.Index(j).Interface()
if cast.ToString(value) == "" {
continue
}
va := url.QueryEscape(cast.ToString(value))
if i == len(r.queryParams)-1 && j == length-1 {
queryParams.WriteString(fmt.Sprintf("%s=%s", v.Name, va))
} else {
queryParams.WriteString(fmt.Sprintf("%s=%s&", v.Name, va))
}
}
} else {
if cast.ToString(v.Value) == "" {
continue
}
va := url.QueryEscape(cast.ToString(v.Value))
if i == len(r.queryParams)-1 {
queryParams.WriteString(fmt.Sprintf("%s=%s", v.Name, va))
} else {
queryParams.WriteString(fmt.Sprintf("%s=%s&", v.Name, va))
}
}
}
return queryParams.String()
}
func (r *Request) AddHeader(key, value string) {
r.c.lock.Lock()
defer r.c.lock.Unlock()
r.headers.Set(key, value)
}
type PathParam struct {
Name string
Value interface{}
}
// Path set path
func (r *Request) Path(path string, args ...PathParam) *Request {
r.path = path
for _, v := range args {
val := reflect.ValueOf(v.Value)
kind := val.Kind()
if kind == reflect.Slice || kind == reflect.Array {
js, err := json.Marshal(v.Value)
if err != nil {
panic(err)
}
path = strings.ReplaceAll(path, "{"+v.Name+"}", cast.ToString(js[1:len(js)-1]))
path = strings.ReplaceAll(path, ":"+v.Name, cast.ToString(js[1:len(js)-1]))
} else {
path = strings.ReplaceAll(path, "{"+v.Name+"}", cast.ToString(v.Value))
path = strings.ReplaceAll(path, ":"+v.Name, cast.ToString(v.Value))
}
}
return r
}
type QueryParam struct {
Name string
Value interface{}
}
func (r *Request) Params(args ...QueryParam) *Request {
if len(args) == 0 {
return r
}
r.queryParams = args
return r
}
// getUrl get url for request
func (r *Request) getUrl() (string, error) {
if r.c.protocol == "" || r.c.addr == "" {
return "", errors.New("invalid url, please check")
}
if r.c.protocol == "https" && r.c.port == "" {
r.c.port = "443"
} else if r.c.protocol == "http" && r.c.port == "" {
r.c.port = "80"
}
return fmt.Sprintf("%s://%s:%s", r.c.protocol, r.c.addr, r.c.port+r.path+r.parseParam()), nil
}
// wsUrl get websocket url for request
func (r *Request) getWsUrl() (string, error) {
if r.c.protocol == "" || r.c.addr == "" || r.c.port == "" {
return "", errors.New("invalid url, you may not login")
}
// upgrade http to websocket proto
if r.c.protocol == "https" {
r.c.protocol = "wss"
} else {
r.c.protocol = "ws"
}
return fmt.Sprintf("%s://%s:%s", r.c.protocol, r.c.addr, r.c.port+r.path+r.parseParam()), nil
}
// Body makes the request use obj as the body. Optional.
// If obj is a string, try to read a file of that name.
// If obj is a []byte, send it directly.
// default marshal it
func (r *Request) Body(obj interface{}) *Request {
if r.err != nil {
return r
}
switch t := obj.(type) {
case io.Reader:
r.body = t
case io.ReadCloser:
r.body = t
case string:
r.body = bytes.NewReader([]byte(t))
case []byte:
r.body = bytes.NewReader(t)
default:
data, err := json.Marshal(obj)
if err != nil {
r.err = err
return r
}
r.body = bytes.NewReader(data)
}
return r
}
// Result contains the result of calling Request.Do().
type Result struct {
body []byte
err error
statusCode int
status string
}
// Do format and executes the request. Returns a Result object for easy response
// processing.
//
// Error type:
// http.Client.Do errors are returned directly.
func (r *Request) Do(ctx context.Context) Result {
if err := r.c.executeRequestMiddlewares(r); err != nil {
return Result{err: err}
}
defaultUrl, err := r.getUrl()
if err != nil {
return Result{err: err}
}
request, err := http.NewRequestWithContext(ctx, r.verb, defaultUrl, r.body)
if err != nil {
return Result{err: err}
}
if r.c.client == nil {
r.c.client = http.DefaultClient
}
if r.c.retryTimes == 0 {
r.c.retryTimes = 1
}
request.Header = r.headers
var rawResp *http.Response
// if meet error, retry times that you set
for k := 0; k < r.c.retryTimes; k++ {
rawResp, err = r.doRequest(r.c.client, request)
if err != nil {
// sleep retry delay
time.Sleep(r.c.retryDelay)
continue
}
break
}
if err != nil {
return Result{err: err}
}
if rawResp == nil {
return Result{err: errors.New("http response is nil")}
}
data, err := io.ReadAll(rawResp.Body)
if err != nil {
return Result{err: err}
}
defer rawResp.Body.Close()
return Result{
body: data,
err: err,
statusCode: rawResp.StatusCode,
status: rawResp.Status,
}
}
func (r *Request) WsConn(ctx context.Context) (*websocket.Conn, *http.Response, error) {
wsUrl, err := r.getWsUrl()
if err != nil {
return nil, nil, err
}
return websocket.DefaultDialer.DialContext(ctx, wsUrl, r.c.headers)
}
func (r *Request) doRequest(client *http.Client, request *http.Request) (*http.Response, error) {
res, err := client.Do(request)
if err != nil {
return nil, err
}
if res == nil {
return nil, errors.New("response is nil")
}
return res, nil
}
type IntoOptions struct {
WrapCodeMsg bool
WrapCodeMsgMapping struct {
CodeField string
DataField string
MsgField string
}
}
// Into stores the result into obj, if possible. If obj is nil it is ignored.
func (r Result) Into(obj interface{}, options *IntoOptions) error {
if reflect.TypeOf(obj).Kind() != reflect.Ptr {
return errors.New("object is not a ptr")
}
if r.err != nil {
return r.err
}
if options != nil {
if options.WrapCodeMsg && options.WrapCodeMsgMapping.CodeField == "" {
options.WrapCodeMsgMapping.CodeField = DefaultCodeField
}
if options.WrapCodeMsg && options.WrapCodeMsgMapping.DataField == "" {
options.WrapCodeMsgMapping.DataField = DefaultDataField
}
if options.WrapCodeMsg && options.WrapCodeMsgMapping.MsgField == "" {
options.WrapCodeMsgMapping.MsgField = DefaultMessageField
}
}
if r.StatusCode() != http.StatusOK {
s := string(r.body)
if len(s) == 0 {
return fmt.Errorf("empty response body, status code: %d", r.StatusCode())
}
if options != nil && options.WrapCodeMsg {
j, err := simplejson.NewJson(r.body)
if err != nil {
return fmt.Errorf("marsher json error: %v, response body: %v", err, r.body)
}
message, _ := j.Get(options.WrapCodeMsgMapping.MsgField).String()
return errors.New(message)
}
return errors.New(s)
}
j, err := simplejson.NewJson(r.body)
if err != nil {
return err
}
var marshalJSON []byte
if options.WrapCodeMsg {
code, err := j.Get(options.WrapCodeMsgMapping.CodeField).Int()
if err != nil {
return err
}
if code != http.StatusOK {
message, _ := j.Get(options.WrapCodeMsgMapping.MsgField).String()
return fmt.Errorf(message)
}
data := j.Get(options.WrapCodeMsgMapping.DataField)
marshalJSON, err = data.MarshalJSON()
if err != nil {
return err
}
} else {
marshalJSON, err = j.MarshalJSON()
if err != nil {
return err
}
}
switch v := obj.(type) {
case proto.Message:
parser := protojson.UnmarshalOptions{
DiscardUnknown: true,
}
err = parser.Unmarshal(marshalJSON, v)
default:
err = json.Unmarshal(marshalJSON, &obj)
}
if err != nil {
return err
}
return nil
}
// Stream proto Stream way return io.ReadCloser
func (r *Request) Stream(ctx context.Context) (io.ReadCloser, error) {
defaultUrl, err := r.getUrl()
if err != nil {
return nil, err
}
request, err := http.NewRequestWithContext(ctx, r.verb, defaultUrl, r.body)
if err != nil {
return nil, err
}
request.Header = r.headers
if r.c.client == nil {
r.c.client = http.DefaultClient
}
if r.c.retryTimes == 0 {
r.c.retryTimes = 1
}
var rawResp *http.Response
// if meet error, retry times that you set
for k := 0; k < r.c.retryTimes; k++ {
rawResp, err = r.doRequest(r.c.client, request)
if err != nil {
// sleep retry delay
time.Sleep(r.c.retryDelay)
continue
}
break
}
if err != nil {
return nil, err
}
if rawResp == nil {
return nil, errors.New("empty resp")
}
if rawResp.StatusCode != 200 {
return nil, errors.Errorf("unhealthy status code: [%d], status message: [%s]", rawResp.StatusCode, rawResp.Status)
}
return rawResp.Body, nil
}
func (r Result) RawResponse() ([]byte, error) {
return r.body, r.err
}
// Error returns the error executing the request, nil if no error occurred.
func (r Result) Error() error {
return r.err
}
// StatusCode returns the HTTP status code of the request. (Only valid if no
// error was returned.)
func (r Result) StatusCode() int {
return r.statusCode
}
// Status returns the status executing the request
func (r Result) Status() string {
return r.status
}