-
Notifications
You must be signed in to change notification settings - Fork 1
/
http.go
97 lines (80 loc) · 2.11 KB
/
http.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
package utils
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"time"
)
var client *http.Client
func httpClient() *http.Client {
if client != nil {
return client
}
t := http.DefaultTransport.(*http.Transport).Clone()
t.MaxIdleConns = 100
t.MaxConnsPerHost = 100
client = &http.Client{
Timeout: time.Second * 30,
Transport: t,
}
return client
}
func HttpGet(ctx context.Context, url, params string, responseModel interface{}) error {
url = fmt.Sprintf("%s?%s", url, params)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json; charset=utf-8")
req.Header.Set("Accept", "application/json; charset=utf-8")
req = req.WithContext(ctx)
res, err := httpClient().Do(req)
if err != nil {
return err
}
defer res.Body.Close()
if res.StatusCode != 200 && res.StatusCode != 201 && res.StatusCode != 204 {
return errors.New("status code: " + res.Status)
}
if responseModel == nil {
return nil
}
//buf := new(bytes.Buffer)
//buf.ReadFrom(res.Body)
//fmt.Println(buf.String())
//return json.Unmarshal(buf.Bytes(), &responseModel)
return json.NewDecoder(res.Body).Decode(&responseModel)
}
func HttpPost(ctx context.Context, url, params string, body, responseModel interface{}) error {
url = fmt.Sprintf("%s?%s", url, params)
var jsonBody []byte
if body != nil {
jsonBody, _ = json.Marshal(&body)
}
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonBody))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json; charset=utf-8")
req.Header.Set("Accept", "application/json; charset=utf-8")
req = req.WithContext(ctx)
res, err := httpClient().Do(req)
if err != nil {
return err
}
defer res.Body.Close()
if res.StatusCode != 200 && res.StatusCode != 201 && res.StatusCode != 204 {
return errors.New("status code: " + res.Status)
}
if responseModel == nil {
return nil
}
//buf := new(bytes.Buffer)
//buf.ReadFrom(res.Body)
//fmt.Println(buf.String())
//json.Unmarshal(buf.Bytes(), &responseModel)
return json.NewDecoder(res.Body).Decode(&responseModel)
}