/
http_client.go
290 lines (261 loc) · 8 KB
/
http_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
/*
*Copyright (c) 2022, kaydxh
*
*Permission is hereby granted, free of charge, to any person obtaining a copy
*of this software and associated documentation files (the "Software"), to deal
*in the Software without restriction, including without limitation the rights
*to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
*copies of the Software, and to permit persons to whom the Software is
*furnished to do so, subject to the following conditions:
*
*The above copyright notice and this permission notice shall be included in all
*copies or substantial portions of the Software.
*
*THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
*IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
*FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
*AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
*LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
*OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
*SOFTWARE.
*/
package http
import (
"bytes"
"context"
"fmt"
"io"
"io/ioutil"
"log"
"net"
"net/http"
"time"
"github.com/gin-gonic/gin/binding"
)
type Client struct {
http.Client
opts struct {
// Timeout specifies a time limit for requests made by this
// Client. The timeout includes connection time, any
// redirects, and reading the response body. The timer remains
// running after Get, Head, Post, or Do return and will
// interrupt reading of the Response.Body.
//
// A Timeout of zero means no timeout.
//
// The Client cancels requests to the underlying Transport
// as if the Request's Context ended.
//
// For compatibility, the Client will also use the deprecated
// CancelRequest method on Transport if found. New
// RoundTripper implementations should use the Request's Context
// for cancellation instead of implementing CancelRequest.
timeout time.Duration
dialTimeout time.Duration
responseHeaderTimeout time.Duration
idleConnTimeout time.Duration
maxIdleConns int
disableKeepAlives bool
// Proxy specifies a function to return a proxy for a given
// Request. If the function returns a non-nil error, the
// request is aborted with the provided error.
//
// The proxy type is determined by the URL scheme. "http",
// "https", and "socks5" are supported. If the scheme is empty,
// "http" is assumed.
//
// If Proxy is nil or returns a nil *URL, no proxy is used.
//proxy func(*http.Request) (*url.URL, error)
// like forward proxy
proxyURL string
// proxyHost is host:port, or domain, replace host in proxy
proxyHost string
// targetHost is host:port, redirct to it, like reverse proxy
targetHost string
ErrorLog *log.Logger
}
}
func NewClient(options ...ClientOption) (*Client, error) {
c := &Client{}
c.ApplyOptions(options...)
transport := DefaultTransportInsecure
/*
transport := &http.Transport{
// ProxyFromEnvironment returns the URL of the proxy to use for a
// given request, as indicated by the environment variables
// HTTP_PROXY, HTTPS_PROXY and NO_PROXY (or the lowercase versions
// thereof). HTTPS_PROXY takes precedence over HTTP_PROXY for https
// requests.
//
// The environment values may be either a complete URL or a
// "host[:port]", in which case the "http" scheme is assumed.
// The schemes "http", "https", and "socks5" are supported.
// An error is returned if the value is a different form.
//
// A nil URL and nil error are returned if no proxy is defined in the
// environment, or a proxy should not be used for the given request,
// as defined by NO_PROXY.
//
// As a special case, if req.URL.Host is "localhost" (with or without
// a port number), then a nil URL and nil error will be returned.
Proxy: http.ProxyFromEnvironment,
// skip verify for https
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
*/
if c.opts.timeout != 0 {
c.Client.Timeout = c.opts.timeout
}
if c.opts.dialTimeout != 0 {
transport.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
conn, err := net.DialTimeout(
network,
addr,
c.opts.dialTimeout,
)
if nil != err {
return nil, err
}
return conn, nil
}
}
if c.opts.responseHeaderTimeout != 0 {
transport.ResponseHeaderTimeout = c.opts.responseHeaderTimeout
}
if c.opts.maxIdleConns != 0 {
transport.MaxIdleConns = c.opts.maxIdleConns
}
if c.opts.idleConnTimeout != 0 {
transport.IdleConnTimeout = c.opts.idleConnTimeout
}
if c.opts.disableKeepAlives {
transport.DisableKeepAlives = c.opts.disableKeepAlives
}
c.Transport = RoundTripFunc(func(req *http.Request) (resp *http.Response, err error) {
if c.opts.proxyURL != "" || c.opts.proxyHost != "" {
transport.Proxy = ProxyFuncFromContextOrEnvironment
proxyUrl := "http://"
if c.opts.proxyURL != "" {
proxyUrl = c.opts.proxyURL
}
proxy := &Proxy{
ProxyUrl: proxyUrl,
ProxyTarget: c.opts.proxyHost,
}
req = RequestWithContextProxy(req, proxy)
}
if c.opts.targetHost != "" {
host := &Host{
HostTarget: c.opts.targetHost,
ReplaceHostInRequest: true,
}
req = RequestWithContextTargetHost(req, host)
}
return RoundTripperWithTarget(transport).RoundTrip(req)
})
return c, nil
}
func (c *Client) Get(ctx context.Context, url string) ([]byte, error) {
r, err := c.get(ctx, url)
if err != nil {
return nil, err
}
defer r.Body.Close()
data, err := ioutil.ReadAll(r.Body)
if err != nil {
return nil, err
}
return data, nil
}
func (c *Client) Post(
ctx context.Context,
url, contentType string,
headers map[string]string,
body []byte,
) ([]byte, error) {
bodyReader := bytes.NewReader(body)
return c.PostReader(ctx, url, contentType, headers, nil, bodyReader)
}
func (c *Client) Put(
ctx context.Context,
url, contentType string,
headers map[string]string,
body []byte,
) ([]byte, error) {
bodyReader := bytes.NewReader(body)
return c.PutReader(ctx, url, contentType, headers, nil, bodyReader)
}
func (c *Client) PostJson(
ctx context.Context,
url string,
headers map[string]string,
body []byte,
) ([]byte, error) {
bodyReader := bytes.NewReader(body)
return c.PostReader(ctx, url, binding.MIMEJSON, headers, nil, bodyReader)
}
func (c *Client) PostPb(
ctx context.Context,
url string,
headers map[string]string,
body []byte,
) ([]byte, error) {
bodyReader := bytes.NewReader(body)
return c.PostReader(ctx, url, binding.MIMEPROTOBUF, headers, nil, bodyReader)
}
func (c *Client) PostJsonWithAuthorize(
ctx context.Context,
url string,
headers map[string]string,
auth func(r *http.Request) error,
body []byte,
) ([]byte, error) {
bodyReader := bytes.NewReader(body)
return c.PostReader(ctx, url, binding.MIMEJSON, headers, auth, bodyReader)
}
func (c *Client) PostReader(
ctx context.Context,
url, contentType string,
headers map[string]string,
auth func(r *http.Request) error,
body io.Reader,
) ([]byte, error) {
return c.HttpReader(ctx, http.MethodPost, url, contentType, headers, auth, body)
}
func (c *Client) PutReader(
ctx context.Context,
url, contentType string,
headers map[string]string,
auth func(r *http.Request) error,
body io.Reader,
) ([]byte, error) {
return c.HttpReader(ctx, http.MethodPut, url, contentType, headers, auth, body)
}
func (c *Client) HttpReader(
ctx context.Context,
method, url, contentType string,
headers map[string]string,
auth func(r *http.Request) error,
body io.Reader,
) ([]byte, error) {
r, err := c.HttpDo(ctx, method, url, contentType, headers, auth, body)
if err != nil {
return nil, err
}
defer r.Body.Close()
data, err := ioutil.ReadAll(r.Body)
if err != nil {
return nil, err
}
if r.StatusCode >= http.StatusBadRequest {
return data, fmt.Errorf("http status code: %v", r.StatusCode)
}
return data, nil
}
func (c *Client) logf(format string, args ...interface{}) {
if c.opts.ErrorLog != nil {
c.opts.ErrorLog.Printf(format, args...)
} else {
log.Printf(format, args...)
}
}