-
Notifications
You must be signed in to change notification settings - Fork 2
/
http_request.go
69 lines (58 loc) · 1.3 KB
/
http_request.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
package helpers
import (
"bytes"
"context"
"encoding/json"
"io/ioutil"
"net/http"
"time"
)
type HttpOptions struct {
Ctx context.Context
Url string
TO *time.Duration
Headers map[string]string
Queries map[string]string
Data []byte
Method string
}
func DoRequest(opt *HttpOptions, rs interface{}) (int, error) {
if opt.TO != nil {
timeout := *opt.TO
ctx, cancel := context.WithTimeout(opt.Ctx, timeout*time.Second)
defer cancel()
opt.Ctx = ctx
}
body := bytes.NewBuffer(opt.Data)
defer body.Reset()
req, err := http.NewRequestWithContext(opt.Ctx, opt.Method, opt.Url, body)
if err != nil {
return http.StatusInternalServerError, err
}
for k, v := range opt.Headers {
req.Header.Set(k, v)
}
queryValues := req.URL.Query()
for key, val := range opt.Queries {
queryValues.Set(key, val)
}
req.URL.RawQuery = queryValues.Encode()
httpClient := &http.Client{}
resp, err := httpClient.Do(req)
if err != nil {
return http.StatusInternalServerError, err
}
defer resp.Body.Close()
if rs == nil {
return resp.StatusCode, nil
}
respBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
return http.StatusInternalServerError, err
}
err = json.Unmarshal(respBody, rs)
if err != nil {
return http.StatusInternalServerError, err
}
return resp.StatusCode, nil
}