-
Notifications
You must be signed in to change notification settings - Fork 0
/
nethttp.go
63 lines (55 loc) · 1.44 KB
/
nethttp.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
package client
import (
"crypto/tls"
rua "github.com/taoxinyi/rua/framework"
"io"
"io/ioutil"
"net/http"
)
// netHttpClient uses net.Http.Client for the requests
type netHttpClient struct {
client *http.Client
request *http.Request
}
// NewNetHttpClient returns a new netHttpClient
// the actual construction is implemented in Init
func NewNetHttpClient() *netHttpClient {
return &netHttpClient{}
}
func (c *netHttpClient) Name() string {
return "net"
}
func (c *netHttpClient) Init(config *rua.LgConfig, request *rua.Request) (err error) {
client := &http.Client{
Timeout: config.Timeout,
Transport: &http.Transport{
MaxIdleConnsPerHost: config.Connections,
TLSClientConfig: &tls.Config{},
}}
c.client = client
c.request = request.HttpRequest
return nil
}
func (c *netHttpClient) CreateUser() (rua.User, error) {
return &netHttpUser{client: c.client, request: c.request}, nil
}
// a netHttpUser just grab a connection from the http.Client and send a requests, and wait for a response
type netHttpUser struct {
client *http.Client
request *http.Request
}
func (u *netHttpUser) DoStaticRequest(response *rua.Response) (err error) {
resp, err := u.client.Do(u.request)
if err != nil {
return err
}
response.StatusCode = resp.StatusCode
// not accurate, only calculated body
// discard the body
n, err := io.Copy(ioutil.Discard, resp.Body)
if err != nil {
return err
}
response.Size = int(n)
return resp.Body.Close()
}