forked from nntaoli-project/goex
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fasthttp_cli.go
68 lines (57 loc) · 1.69 KB
/
fasthttp_cli.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
package httpcli
import (
"errors"
"github.com/valyala/fasthttp"
"github.com/valyala/fasthttp/fasthttpproxy"
"github.com/wfunc/goex/v2/logger"
"time"
)
type FastHttpCli struct {
fastHttpClient *fasthttp.Client
//socksDialer fasthttp.DialFunc
timeout time.Duration
}
func NewFastHttpCli() *FastHttpCli {
cli := &fasthttp.Client{
Name: "github.com/wfunc/goex/v2/",
MaxConnsPerHost: 512,
MaxIdleConnDuration: 20 * time.Second,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
}
return &FastHttpCli{fastHttpClient: cli, timeout: 10 * time.Second}
}
func (cli *FastHttpCli) SetTimeout(sec int64) {
cli.timeout = time.Duration(sec) * time.Second
cli.fastHttpClient.WriteTimeout = cli.timeout
cli.fastHttpClient.ReadTimeout = cli.timeout
}
func (cli *FastHttpCli) SetProxy(proxy string) error {
logger.Infof("[fast http cli] proxy=%s", proxy)
cli.fastHttpClient.Dial = fasthttpproxy.FasthttpSocksDialer(proxy)
return nil
}
func (cli *FastHttpCli) DoRequest(method, rqUrl string, reqBody string, headers map[string]string) (data []byte, err error) {
//logger.Info("[fast http cli] use fasthttp client")
logger.Debug("[fast http cli] req url:", rqUrl)
req := fasthttp.AcquireRequest()
resp := fasthttp.AcquireResponse()
defer func() {
fasthttp.ReleaseRequest(req)
fasthttp.ReleaseResponse(resp)
}()
for k, v := range headers {
req.Header.Set(k, v)
}
req.Header.SetMethod(method)
req.SetRequestURI(rqUrl)
req.SetBodyString(reqBody)
err = cli.fastHttpClient.DoTimeout(req, resp, cli.timeout)
if err != nil {
return nil, err
}
if resp.StatusCode() != 200 {
return nil, errors.New(resp.String())
}
return resp.Body(), nil
}