This repository has been archived by the owner on Aug 17, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttpclient.go
150 lines (132 loc) · 3.29 KB
/
httpclient.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
package otgo
import (
"bytes"
"compress/gzip"
"context"
"crypto/tls"
"encoding/json"
"fmt"
"io/ioutil"
"net"
"net/http"
"net/url"
"strings"
"time"
)
type ctxKey int
const (
// CtxHeaderKey ...
CtxHeaderKey ctxKey = 0
)
var tr = &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: false},
DialContext: (&net.Dialer{
Timeout: 5 * time.Second,
KeepAlive: 25 * time.Second,
}).DialContext,
ForceAttemptHTTP2: true,
MaxIdleConns: 100,
MaxIdleConnsPerHost: 100,
IdleConnTimeout: 59 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 4 * time.Second,
ResponseHeaderTimeout: 10 * time.Second,
}
// Client ...
type Client struct {
*http.Client
Header http.Header
ConstraintEndpoint string // set it for testing purposes only
}
// HTTPClient ...
type HTTPClient interface {
Do(ctx context.Context, method, api string, h http.Header, input, output interface{}) error
}
// NewClient ...
func NewClient(client *http.Client) *Client {
if client == nil {
client = &http.Client{
Transport: tr,
Timeout: time.Second * 5,
}
}
return &Client{Client: client, Header: http.Header{}}
}
// Do ...
func (c *Client) Do(ctx context.Context, method, api string, h http.Header, input, output interface{}) error {
err := ctx.Err()
if err != nil {
return fmt.Errorf("context.Context error: %v", err)
}
var b bytes.Buffer
if input != nil {
if err = json.NewEncoder(&b).Encode(input); err != nil {
return fmt.Errorf("encode input data error: %v", err)
}
}
if c.ConstraintEndpoint != "" {
if strings.HasPrefix(api, "http") {
u, err := url.Parse(api)
if err != nil {
return err
}
api = c.ConstraintEndpoint + u.RequestURI() // override URL endpoint
} else {
api = c.ConstraintEndpoint + api
}
}
req, err := http.NewRequestWithContext(ctx, method, api, &b)
if err != nil {
return fmt.Errorf("create http request error: %v", err)
}
copyHeader(req.Header, c.Header)
if val := ctx.Value(CtxHeaderKey); val != nil {
copyHeader(req.Header, val.(http.Header))
}
if h != nil {
copyHeader(req.Header, h)
}
req.Header.Set("Accept", "application/json")
req.Header.Set("Content-Type", "application/json; charset=utf-8")
req.Header.Set("Accept-Encoding", "gzip")
resp, err := c.Client.Do(req)
if err != nil {
return fmt.Errorf("do http request error: %v", err)
}
defer resp.Body.Close()
body := resp.Body
if resp.Header.Get("Content-Encoding") == "gzip" {
body, err = gzip.NewReader(body)
if err != nil {
return fmt.Errorf("gzip reader error: %v", err)
}
defer body.Close()
}
data, err := ioutil.ReadAll(body)
if err != nil {
return fmt.Errorf("read response error: %s, status code: %v", err.Error(), resp.StatusCode)
}
if output != nil {
if err := json.Unmarshal(data, output); err != nil {
return fmt.Errorf("decoding json error: %s, status code: %v, response: %s", err.Error(), resp.StatusCode, string(data))
}
}
if resp.StatusCode >= 300 {
return fmt.Errorf("non-success response, status code: %v, response: %s",
resp.StatusCode, string(data))
}
return nil
}
func copyHeader(dst http.Header, src http.Header) {
for k, vv := range src {
switch len(vv) {
case 1:
dst.Set(k, vv[0])
default:
dst.Del(k)
for _, v := range vv {
dst.Add(k, v)
}
}
}
}