-
Notifications
You must be signed in to change notification settings - Fork 0
/
http_client.go
93 lines (76 loc) · 1.76 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
package main
import (
"errors"
"io"
"net"
"net/http"
"sync/atomic"
"time"
"go.uber.org/zap"
)
const (
ErrHttpClientDoFailed = ErrCategoryHttp + 1
ErrIOUtilReadAllFailed = ErrCategoryHttp + 2
ErrCloseHttpResp = ErrCategoryHttp + 3
ErrReadHttpRespTimeout = ErrCategoryHttp + 4
)
var transport = &http.Transport{
DialContext: (&net.Dialer{
Timeout: 300 * time.Second,
KeepAlive: 1200 * time.Second,
}).DialContext,
MaxIdleConns: 1200,
IdleConnTimeout: 600 * time.Second,
ExpectContinueTimeout: 600 * time.Second,
MaxIdleConnsPerHost: 300,
}
var httpClient = &http.Client{Transport: transport}
func doHttpRequest(req *http.Request, dropHttpResp bool) Result {
var r Result
if p.SyncConcurrency {
atomic.AddInt32(&concurrency, 1)
r.Concurrency = concurrency
} else {
r.Concurrency = int32(p.Goroutines)
}
r.S = time.Now()
resp, err := httpClient.Do(req)
r.E = time.Now()
if p.SyncConcurrency {
atomic.AddInt32(&concurrency, -1)
}
r.Latency = r.E.Sub(r.S).Microseconds()
if err != nil {
r.Ret = ErrHttpClientDoFailed
r.Err = err
return r
}
r.HttpStatusCode = resp.StatusCode
respBodyChan := make(chan string, 1)
go func() {
body, readAllErr := io.ReadAll(resp.Body)
if readAllErr != nil {
r.Ret = ErrIOUtilReadAllFailed
r.Err = readAllErr
}
respBodyChan <- string(body)
}()
select {
case <-time.After(time.Duration(p.ReadHttpRespTimeout) * time.Second):
r.Ret = ErrReadHttpRespTimeout
r.Err = errors.New("read http response timeout")
case respBody := <-respBodyChan:
if p.Verbose {
logger.Debug("http response", zap.String("body", respBody))
}
if !dropHttpResp {
r.Resp = respBody
}
}
err = resp.Body.Close()
if err != nil {
r.Ret = ErrCloseHttpResp
r.Err = err
}
return r
}