-
Notifications
You must be signed in to change notification settings - Fork 2
/
api_http.go
55 lines (44 loc) · 1.22 KB
/
api_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
package api
import (
"errors"
"github.com/valyala/fasthttp"
"net"
"net/http"
"time"
)
const HttpTTL = 1 * time.Minute
var FastClient = CreateFastHttpClient()
func CreateFastHttpClient() fasthttp.Client {
var defaultDialer = &fasthttp.TCPDialer{Concurrency: 300}
return fasthttp.Client{
Dial: func(addr string) (net.Conn, error) {
idx := 3 // 重试三次
for {
idx--
conn, err := defaultDialer.DialTimeout(addr, 10*time.Second) // tcp连接超时时间10s
if err != fasthttp.ErrDialTimeout || idx == 0 {
return conn, err
}
}
},
}
}
func Post(req []byte) ([]byte, error) {
var resp []byte
httpReq := fasthttp.AcquireRequest()
defer fasthttp.ReleaseRequest(httpReq)
httpResp := fasthttp.AcquireResponse()
defer fasthttp.ReleaseResponse(httpResp)
httpReq.SetRequestURI(ApiUrl)
httpReq.Header.SetContentType("application/json;charset=utf-8")
httpReq.SetBody(req)
httpReq.Header.SetMethod(http.MethodPost)
if err := FastClient.DoTimeout(httpReq, httpResp, HttpTTL); err != nil {
return resp, err
}
resp = httpResp.Body()
if len(resp) == 0 { // 避免 json.Unmarshal 出现 unexpected end of JSON input 错误
return resp, errors.New("http resp body is nil")
}
return resp, nil
}