forked from rakyll/hey
-
Notifications
You must be signed in to change notification settings - Fork 0
/
request_factory.go
66 lines (58 loc) · 1.32 KB
/
request_factory.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
package main
import (
"bytes"
"encoding/json"
"io"
"math/rand"
"net/http"
"strings"
"time"
)
func generateRequest(requestParam request) *http.Request {
req, err := http.NewRequest(
strings.ToUpper(requestParam.Method),
requestParam.Url,
nil,
)
if err != nil {
usageAndExit("invalid request param")
}
header := make(http.Header)
header.Set("Content-Type", *contentType)
if len(requestParam.Headers) > 0 {
for key, value := range requestParam.Headers {
header.Set(key, value)
}
}
req.Header = header
if len(requestParam.Cookies) > 0 {
for key, value := range requestParam.Cookies {
req.AddCookie(&http.Cookie{
Name: key,
Value: value,
})
}
}
if requestParam.Username != "" || requestParam.Password != "" {
req.SetBasicAuth(requestParam.Username, requestParam.Password)
}
if requestParam.Host != "" {
req.Host = requestParam.Host
}
if requestParam.Body != nil {
data, err := json.Marshal(requestParam.Body)
if err != nil {
usageAndExit(err.Error())
}
req.Body = io.NopCloser(bytes.NewReader(data))
}
return req
}
func requestFactory(config config) func() *http.Request {
rand.Seed(time.Now().UnixNano())
return func() *http.Request {
index := rand.Intn(len(config.Requests))
randomRequestParam := config.Requests[index]
return generateRequest(randomRequestParam)
}
}