forked from adjust/go-wrk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
98 lines (81 loc) · 1.97 KB
/
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
package main
import (
"crypto/tls"
"crypto/x509"
"io/ioutil"
"log"
"net/http"
"net/url"
"strings"
"sync"
)
func StartClient(url_, heads, requestBody string, meth string, dka bool, responseChan chan *Response, waitGroup *sync.WaitGroup, tc int) {
defer waitGroup.Done()
var tr *http.Transport
u, err := url.Parse(url_)
if err == nil && u.Scheme == "https" {
var tlsConfig *tls.Config
if *insecure {
tlsConfig = &tls.Config{
InsecureSkipVerify: true,
}
} else {
// Load client cert
cert, err := tls.LoadX509KeyPair(*certFile, *keyFile)
if err != nil {
log.Fatal(err)
}
// Load CA cert
caCert, err := ioutil.ReadFile(*caFile)
if err != nil {
log.Fatal(err)
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)
// Setup HTTPS client
tlsConfig = &tls.Config{
Certificates: []tls.Certificate{cert},
RootCAs: caCertPool,
}
tlsConfig.BuildNameToCertificate()
}
tr = &http.Transport{TLSClientConfig: tlsConfig, DisableKeepAlives: dka}
} else {
tr = &http.Transport{DisableKeepAlives: dka}
}
requestBodyReader := strings.NewReader(requestBody)
req, _ := http.NewRequest(meth, url_, requestBodyReader)
sets := strings.Split(heads, "\n")
//Split incoming header string by \n and build header pairs
for i := range sets {
split := strings.SplitN(sets[i], ":", 2)
if len(split) == 2 {
req.Header.Set(split[0], split[1])
}
}
timer := NewTimer()
for {
timer.Reset()
resp, err := tr.RoundTrip(req)
respObj := &Response{}
if err != nil {
respObj.Error = true
} else {
if resp.ContentLength < 0 { // -1 if the length is unknown
data, err := ioutil.ReadAll(resp.Body)
if err == nil {
respObj.Size = int64(len(data))
}
} else {
respObj.Size = resp.ContentLength
}
respObj.StatusCode = resp.StatusCode
resp.Body.Close()
}
respObj.Duration = timer.Duration()
if len(responseChan) >= tc {
break
}
responseChan <- respObj
}
}