-
Notifications
You must be signed in to change notification settings - Fork 8
/
config.go
325 lines (284 loc) · 6.96 KB
/
config.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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
package pit
import (
"bytes"
"crypto/tls"
"fmt"
"io/ioutil"
"log"
"net"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/dgrr/http2"
"github.com/valyala/fasthttp"
)
// Config holds httpit settings
type Config struct {
// Connections indicates how many tcp connections are used concurrently
Connections int
// Count is numbers of request in one benchmark round
Count int
// Qps specifies the highest value for a fixed benchmark, but the real qps
// may lower than it
Qps int
// Duration means benchmark duration, it's ignored if Count is specified
Duration time.Duration
// Timeout indicates socket/request timeout
Timeout time.Duration
// Url is the benchmark target
Url string
// Method is the http method
Method string
// Args can set data handily for form and json request
Args []string
// Headers indicates http headers
Headers []string
// Host can override Host header in request
Host string
// DisableKeepAlives sets Connection header to 'close'
DisableKeepAlives bool
// Body is request body
Body string
// File indicates that read request body from a file
File string
// Stream indicates using stream body
Stream bool
// JSON indicates send a JSON request
JSON bool
// JSON indicates send a Form request
Form bool
// Insecure skips tls verification
Insecure bool
// Cert indicates path to the client's TLS Certificate
Cert string
// Cert indicates path to the client's TLS Certificate private key
Key string
// HttpProxy indicates an http proxy address
HttpProxy string
// SocksProxy indicates an socks proxy address
SocksProxy string
// Pipeline if true, will use fasthttp PipelineClient
Pipeline bool
// Follow if true, follow 30x location redirects in debug mode
Follow bool
// MaxRedirects indicates maximum redirect count of following 30x,
// default is 30 (only works if Follow is true)
MaxRedirects int
// Debug if true, only send request once and show request and response detail
Debug bool
// Http2 if true, will use http2 for fasthttp
Http2 bool
throughput int64
body []byte
isTLS bool
addr string
tlsConf *tls.Config
}
func (c *Config) doer() (clientDoer, error) {
if c.Pipeline {
return &fasthttp.PipelineClient{
Name: "httpit/" + Version,
Addr: c.addr,
Dial: c.getDialer(),
IsTLS: c.isTLS,
TLSConfig: c.tlsConf,
MaxConns: c.Connections,
ReadTimeout: c.Timeout,
Logger: discardLogger{},
}, nil
}
return c.hostClient()
}
func (c *Config) hostClient() (*fasthttp.HostClient, error) {
hc := &fasthttp.HostClient{
Name: "httpit/" + Version,
Addr: c.addr,
Dial: c.getDialer(),
IsTLS: c.isTLS,
TLSConfig: c.tlsConf,
MaxConns: c.Connections,
ReadTimeout: c.Timeout,
}
if c.Http2 {
log.Println("setup http2")
if err := http2.ConfigureClient(hc, http2.ClientOpts{}); err != nil {
return nil, fmt.Errorf("%s doesn't support http/2\n", hc.Addr)
}
}
return hc, nil
}
func (c *Config) setReqBasic(req *fasthttp.Request) (err error) {
req.Header.SetMethod(c.Method)
req.SetRequestURI(c.Url)
uri := req.URI()
host := uri.Host()
scheme := uri.Scheme()
if bytes.Equal(scheme, strHTTPS) {
c.isTLS = true
} else if !bytes.Equal(scheme, strHTTP) {
err = fmt.Errorf("unsupported protocol %q. http and https are supported", scheme)
return
}
c.addr = addMissingPort(string(host), c.isTLS)
return
}
var (
strHTTP = []byte("http")
strHTTPS = []byte("https")
)
func addMissingPort(addr string, isTLS bool) string {
n := strings.Index(addr, ":")
if n >= 0 {
return addr
}
port := 80
if isTLS {
port = 443
}
return net.JoinHostPort(addr, strconv.Itoa(port))
}
func (c *Config) setReqBody(req *fasthttp.Request) (err error) {
if c.Body != "" {
c.body = []byte(c.Body)
}
if c.File != "" {
c.body, err = ioutil.ReadFile(filepath.Clean(c.File))
}
if !c.Stream {
// set constant body
req.SetBody(c.body)
}
return
}
// parseArgs gets body from extra args
func (c *Config) parseArgs() {
if len(c.Args) == 0 {
return
}
isJson := true
for _, arg := range c.Args {
formEqualIndex := strings.Index(arg, "=")
jsonEqualIndex := strings.Index(arg, ":=")
// no "=" or "=" is before ":="
if formEqualIndex == -1 || jsonEqualIndex == -1 || formEqualIndex < jsonEqualIndex {
isJson = false
}
}
if isJson {
c.JSON = true
c.body = append(c.body, '{')
for ii, arg := range c.Args {
i := strings.Index(arg, ":=")
k, v := strings.TrimSpace(arg[:i]), strings.TrimSpace(arg[i+2:])
c.body = append(c.body, '"')
c.body = append(c.body, k...)
c.body = append(c.body, '"', ':')
b := needQuote(v)
if b {
c.body = append(c.body, '"')
}
c.body = append(c.body, v...)
if b {
c.body = append(c.body, '"')
}
if ii < len(c.Args)-1 {
c.body = append(c.body, ',')
}
}
c.body = append(c.body, '}')
} else {
c.Form = true
c.Method = fasthttp.MethodPost
formArgs := fasthttp.AcquireArgs()
for _, arg := range c.Args {
i := strings.Index(arg, "=")
if i == -1 {
formArgs.AddNoValue(strings.TrimSpace(arg))
} else {
formArgs.Add(strings.TrimSpace(arg[:i]), strings.TrimSpace(arg[i+1:]))
}
}
c.body = formArgs.AppendBytes(c.body)
fasthttp.ReleaseArgs(formArgs)
}
}
func needQuote(v string) bool {
if vv := strings.ToLower(v); vv == "false" || vv == "true" {
return false
}
if _, err := strconv.Atoi(v); err == nil {
return false
}
if _, err := strconv.ParseFloat(v, 64); err == nil {
return false
}
l := len(v)
if l <= 1 {
return true
}
if (v[0] == '[' && v[l-1] == ']') || (v[0] == '{' && v[l-1] == '}') {
return false
}
return true
}
func (c *Config) setReqHeader(req *fasthttp.Request) (err error) {
if err = headers(c.Headers).writeToFasthttp(req); err != nil {
return
}
if c.DisableKeepAlives {
req.Header.SetConnectionClose()
}
if c.Host != "" {
req.URI().SetHost(c.Host)
}
if c.JSON {
req.Header.SetContentType(MIMEApplicationJSON)
}
if c.Form {
req.Header.SetContentType(MIMEApplicationForm)
}
return
}
func (c *Config) getDialer() fasthttp.DialFunc {
if c.HttpProxy != "" {
return fasthttpHttpProxyDialer(&c.throughput, c.HttpProxy, c.Timeout)
}
if c.SocksProxy != "" {
return fasthttpSocksProxyDialer(&c.throughput, c.SocksProxy)
}
return fasthttpDialer(&c.throughput, c.Timeout)
}
/* #nosec G402 */
func (c *Config) getTlsConfig() (conf *tls.Config, err error) {
var certs []tls.Certificate
if certs, err = readClientCert(c.Cert, c.Key); err != nil {
return
}
conf = &tls.Config{
Certificates: certs,
InsecureSkipVerify: c.Insecure,
}
return
}
func readClientCert(certPath, keyPath string) (certs []tls.Certificate, err error) {
if certPath == "" && keyPath == "" {
return
}
var cert tls.Certificate
if cert, err = tls.LoadX509KeyPair(certPath, keyPath); err != nil {
return
}
certs = append(certs, cert)
return
}
func (c *Config) getMaxRedirects() int {
if !c.Follow {
return 0
}
n := c.MaxRedirects
if n <= 0 {
n = defaultMaxRedirects
}
return n
}