forked from nntaoli-project/goex
-
Notifications
You must be signed in to change notification settings - Fork 0
/
default_http_client.go
110 lines (92 loc) · 2.5 KB
/
default_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
package httpcli
import (
"context"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"strings"
"time"
"github.com/wfunc/goex/logger"
)
var Cli IHttpClient
func init() {
Cli = NewDefaultHttpClient()
}
type DefaultHttpClient struct {
cli *http.Client
timeout time.Duration
}
func NewDefaultHttpClient() *DefaultHttpClient {
cli := new(DefaultHttpClient)
cli.init()
return cli
}
func (cli *DefaultHttpClient) init() {
logger.Info("[http utils] setup default http client")
cli.timeout = 5 * time.Second
cli.cli = &http.Client{
Timeout: cli.timeout,
Transport: &http.Transport{
IdleConnTimeout: time.Minute,
TLSHandshakeTimeout: cli.timeout,
ResponseHeaderTimeout: cli.timeout,
MaxConnsPerHost: 4,
MaxIdleConnsPerHost: 4,
MaxIdleConns: 8,
},
}
}
func (cli *DefaultHttpClient) SetTimeout(sec int64) {
timeout := time.Duration(sec) * time.Second
cli.timeout = timeout
logger.Infof("[DefaultHttpClient] http(s) timeout: %s", timeout.String())
cli.cli.Timeout = timeout
trans := cli.cli.Transport.(*http.Transport)
trans.ResponseHeaderTimeout = timeout
trans.TLSHandshakeTimeout = timeout
trans.ExpectContinueTimeout = timeout
}
func (cli *DefaultHttpClient) SetProxy(proxy string) error {
proxyUrl, err := url.Parse(proxy)
if err != nil {
logger.Warnf("[DefaultHttpClient] parse proxy url err: %s", err.Error())
return err
}
logger.Infof("[DefaultHttpClient] http(s) proxy url: %s", proxy)
trans := cli.cli.Transport.(*http.Transport)
trans.Proxy = func(request *http.Request) (*url.URL, error) {
return proxyUrl, nil
}
return nil
}
func (cli *DefaultHttpClient) DoRequest(method, rqUrl string, reqBody string, headers map[string]string) (data []byte, err error) {
logger.Debugf("[DefaultHttpClient] [%s] request url: %s", method, rqUrl)
reqTimeoutCtx, _ := context.WithTimeout(context.TODO(), cli.timeout)
req, _ := http.NewRequestWithContext(reqTimeoutCtx, method, rqUrl, strings.NewReader(reqBody))
if headers != nil {
for k, v := range headers {
req.Header.Add(k, v)
}
}
resp, err := cli.cli.Do(req)
if err != nil {
return nil, err
}
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
logger.Error("[DefaultHttpClient] close response body error:", err.Error())
}
}(resp.Body)
bodyData, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("read response body error: %w", err)
}
if resp.StatusCode != 200 {
return bodyData, errors.New(resp.Status)
}
return bodyData, nil
}