-
Notifications
You must be signed in to change notification settings - Fork 108
/
Copy pathclient.go
125 lines (102 loc) · 2.58 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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
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}
}
timer := NewTimer()
hdrs, _ := buildHeaders(heads)
for {
requestBodyReader := strings.NewReader(requestBody)
req, _ := http.NewRequest(meth, url_, requestBodyReader)
for key, vals := range hdrs {
for _, val := range vals {
req.Header.Set(key, val)
}
}
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
if *respContains != "" {
data, err := ioutil.ReadAll(resp.Body)
if err == nil {
respObj.Body = string(data)
}
}
}
respObj.StatusCode = resp.StatusCode
resp.Body.Close()
}
respObj.Duration = timer.Duration()
if len(responseChan) >= tc {
break
}
responseChan <- respObj
}
}
// buildHeaders build the HTTP Request headers from the parsed flag -H or
// from the default header set.
// The headers are "set" (not added), thus same key values get replaced.
// Note: if a key has no value, it is not added into the Headers, by original
// package design.
func buildHeaders(heads string) (http.Header, error) {
heads = strings.Replace(heads, `\n`, "\n", -1)
h := http.Header{}
sets := strings.Split(heads, "\n")
for i := range sets {
split := strings.SplitN(sets[i], ":", 2)
if len(split) == 2 {
h.Set(split[0], split[1])
}
}
return h, nil
}