forked from parkghost/gohttpbench
-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
192 lines (159 loc) · 4.53 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
package main
import (
"errors"
"flag"
"fmt"
"io/ioutil"
"net/url"
"os"
"regexp"
"runtime"
"strconv"
"strings"
"time"
)
type Config struct {
requests int
concurrency int
timelimit int
executionTimeout time.Duration
method string
bodyContent []byte
contentType string
headers []string
cookies []string
gzip bool
keepAlive bool
basicAuthentication string
userAgent string
url string
host string
port int
}
func LoadConfig() (config *Config, err error) {
// setup command-line flags
flag.IntVar(&Verbosity, "v", 0, "How much troubleshooting info to print")
flag.IntVar(&GoMaxProcs, "G", runtime.NumCPU(), "Number of CPU")
flag.BoolVar(&ContinueOnError, "r", false, "Don't exit when errors")
request := flag.Int("n", 1, "Number of requests to perform")
concurrency := flag.Int("c", 1, "Number of multiple requests to make")
timelimit := flag.Int("t", 0, "Seconds to max. wait for responses")
postFile := flag.String("p", "", "File containing data to POST. Remember also to set -T")
putFile := flag.String("u", "", "File containing data to PUT. Remember also to set -T")
headMethod := flag.Bool("i", false, "Use HEAD instead of GET")
contentType := flag.String("T", "text/plain", "Content-type header for POSTing, eg. 'application/x-www-form-urlencoded' Default is 'text/plain'")
var headers, cookies stringSet
flag.Var(&headers, "H", "Add Arbitrary header line, eg. 'Accept-Encoding: gzip' Inserted after all normal header lines. (repeatable)")
flag.Var(&cookies, "C", "Add cookie, eg. 'Apache=1234. (repeatable)")
basicAuthentication := flag.String("A", "", "Add Basic WWW Authentication, the attributes are a colon separated username and password.")
keepAlive := flag.Bool("k", false, "Use HTTP KeepAlive feature")
gzip := flag.Bool("z", false, "Use HTTP Gzip feature")
showHelp := flag.Bool("h", false, "Display usage information (this message)")
flag.Usage = func() {
fmt.Print("Usage: gb [options] http[s]://hostname[:port]/path\nOptions are:\n")
flag.PrintDefaults()
}
flag.Parse()
if *showHelp {
flag.Usage()
os.Exit(0)
}
if flag.NArg() != 1 {
flag.Usage()
os.Exit(-1)
}
urlStr := strings.Trim(strings.Join(flag.Args(), ""), " ")
isURL, _ := regexp.MatchString(`http.*?://.*`, urlStr)
if !isURL {
flag.Usage()
os.Exit(-1)
}
// build configuration
config = &Config{}
config.requests = *request
config.concurrency = *concurrency
switch {
case *postFile != "":
config.method = "POST"
if err = loadFile(config, *postFile); err != nil {
return
}
case *putFile != "":
config.method = "PUT"
if err = loadFile(config, *putFile); err != nil {
return
}
case *headMethod:
config.method = "HEAD"
default:
config.method = "GET"
}
if *timelimit > 0 {
config.timelimit = *timelimit
if config.requests == 1 {
config.requests = MaxRequests
}
}
config.executionTimeout = MaxExecutionTimeout
config.contentType = *contentType
config.keepAlive = *keepAlive
config.gzip = *gzip
config.basicAuthentication = *basicAuthentication
config.headers = []string(headers)
config.cookies = []string(cookies)
config.userAgent = "GoHttpBench/" + GBVersion
URL, err := url.Parse(urlStr)
if err != nil {
return
}
config.host, config.port = extractHostAndPort(URL)
config.url = urlStr
if Verbosity > 1 {
fmt.Printf("dump config: %#+v\n", config)
}
// validate configuration
if config.requests < 1 || config.concurrency < 1 || config.timelimit < 0 || GoMaxProcs < 1 || Verbosity < 0 {
err = errors.New("wrong number of arguments")
return
}
if config.concurrency > config.requests {
err = errors.New("Cannot use concurrency level greater than total number of requests")
return
}
return
}
func loadFile(config *Config, filename string) error {
bytes, err := ioutil.ReadFile(filename)
if err != nil {
return err
}
config.bodyContent = bytes
return nil
}
type stringSet []string
func (f *stringSet) String() string {
return fmt.Sprint([]string(*f))
}
func (f *stringSet) Set(value string) error {
*f = append(*f, value)
return nil
}
func extractHostAndPort(url *url.URL) (host string, port int) {
hostname := url.Host
pos := strings.LastIndex(hostname, ":")
if pos > 0 {
portInt64, _ := strconv.Atoi(hostname[pos+1:])
host = hostname[0:pos]
port = int(portInt64)
} else {
host = hostname
if url.Scheme == "http" {
port = 80
} else if url.Scheme == "https" {
port = 443
} else {
panic("unsupported protocol schema:" + url.Scheme)
}
}
return
}