-
Notifications
You must be signed in to change notification settings - Fork 4
/
hat.go
436 lines (373 loc) · 11.7 KB
/
hat.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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
/*
* A CLI tool for HTTP API Testing
* https://www.likexian.com/
*
* Copyright 2014-2015, Li Kexian
* Released under the Apache License, Version 2.0
*
*/
package main
import (
"fmt"
"os"
"strings"
"net/http"
"io/ioutil"
"bytes"
"strconv"
"net/url"
"time"
"errors"
"github.com/likexian/simplejson-go"
)
const (
VERSION = "0.8.4"
HELP_INFO = `Usage:
hat [FLAGS] [METHOD] [URL] [OPTIONS]
FLAGS: specify data type of POST and PUT
-j, --json POST/PUT data as json encode (default)
-f, --form POST/PUT data as form encode
FLAGS specify verbose
-v, --verbose
FLAGS specify show request/response time and download speed
-t
FLAGS specify request and response total timeout
--timeout=<int>
FLAGS specify show the version
-V, --version
FLAGS specify show the help
-h, --help
METHOD: specify http request method
GET HTTP GET GET / HTTP/1.1 (default)
POST HTTP POST POST / HTTP/1.1
PUT HTTP PUT PUT / HTTP/1.1
DELETE HTTP DELETE DELETE / HTTP/1.1
URL: the HTTP URL for request, support http and https
<empty> for http://127.0.0.1/ (default)
:8080 for http://127.0.0.1:8080/
:8080/api/ for http://127.0.0.1:8080/api/
/api/ for http://127.0.0.1/api/
OPTIONS: the HTTP headers and HTTP body, add as many as you want
key:value HTTP headers for example User-Agent:HAT/0.1.0
key=value HTTP body for example name=likexian
key?=value HTTP query for example name?=likexian set URL to /?name=likexian
@file HTTP POST/PUT Data for example @post.json will use post.json content as post/put body data
`
URL_DEFAULT = "http://127.0.0.1"
)
type Param struct {
Verbose bool `json:"verbose"`
Timer bool `json:"timer"`
Timeout int `json:"timeout"`
IsJson bool `json:"is_json"`
Method string `json:"method"`
URL string `json:"url"`
Header map[string]string `json:"header"`
Query map[string]string `json:"query"`
Data map[string]string `json:"data"`
RawData string `json:"raw_data"`
}
func Version() string {
return VERSION
}
func Author() string {
return "[Li Kexian](https://www.likexian.com/)"
}
func Copyright() string {
return "Copyright 2014-2015, Li Kexian"
}
func License() string {
return "Apache License, Version 2.0"
}
func main() {
param := Param{
false,
false,
30,
true,
"GET",
URL_DEFAULT,
map[string]string{},
map[string]string{},
map[string]string{},
"",
}
args := os.Args
for i:=1; i<len(args); i++ {
v := args[i]
if v[0] == ':' || v[0] == '/' {
param.URL = URL_DEFAULT + v
continue
}
if v[0] == '@' {
b_text, err := ioutil.ReadFile(v[1:])
if err != nil {
fmt.Println(err)
os.Exit(1)
}
text := string(b_text)
param.IsJson = false
if text != "" && (text[0] == '{' || text[0] == '[') && (text[len(text) - 1] == '}' || text[len(text) - 1] == ']') {
_, err := simplejson.Loads(text)
if err == nil {
param.IsJson = true
}
}
param.Method = "POST"
param.RawData = text
continue
} else if v[0] == '-' {
if v == "-j" || v == "--json" {
param.IsJson = true
continue
} else if v == "-f" || v == "--form" {
param.IsJson = false
continue
}
if v == "-v" || v == "--verbose" {
param.Verbose = true
continue
}
if v == "-t" {
param.Timer = true
continue
}
if len(v) > 10 && v[:10] == "--timeout=" {
timeout, err := strconv.Atoi(v[10:])
if err != nil {
fmt.Println(err)
os.Exit(1)
}
param.Timeout = timeout
continue
}
if v == "-V" || v == "--version" {
fmt.Println("HAT version " + Version())
fmt.Println(Copyright())
fmt.Println(License())
os.Exit(0)
}
if v == "-h" || v == "--help" {
fmt.Println(HELP_INFO)
os.Exit(0)
}
continue
}
if len(v) < 7 {
_v := strings.ToUpper(v)
if _v == "GET" || _v == "POST" || _v == "PUT" || _v == "DELETE" {
param.Method = _v
continue
}
}
if len(v) > 7 && v[:7] == "http://" {
param.URL = v
continue
} else if len(v) > 8 && v[:8] == "https://" {
param.URL = v
continue
}
if strings.Contains(v, "?=") {
vv := strings.SplitN(v, "?=", 2)
if !strings.Contains(vv[0], "=") && !strings.Contains(vv[0], ":") {
param.Query[vv[0]] = vv[1]
continue
}
}
if strings.Contains(v, "=") {
vv := strings.SplitN(v, "=", 2)
if !strings.Contains(vv[0], ":") {
param.Data[vv[0]] = vv[1]
continue
}
}
if strings.Contains(v, ":") {
vv := strings.SplitN(v, ":", 2)
_v := vv[1]
if strings.Contains(vv[1], "/") {
_vv := strings.SplitN(vv[1], "/", 2)
_v = _vv[0]
}
if len(_v) > 0 && len(_v) < 6 {
_, err := strconv.Atoi(_v)
if err == nil {
param.URL = v
continue
}
}
param.Header[strings.ToLower(vv[0])] = vv[1]
continue
}
param.URL = v
}
HttpRequest(param)
}
func HttpRequest(param Param) {
if len(param.URL) <= 7 || (param.URL[:8] != "https://" && param.URL[:7] != "http://") {
param.URL = "http://" + param.URL
}
q_data := url.Values{}
for k, v := range param.Query {
q_data.Add(k, v)
}
q_query := q_data.Encode()
if q_query != "" {
if !strings.Contains(param.URL, "?") {
param.URL += "?" + q_query
} else {
param.URL += "&" + q_query
}
}
w_body := ""
v_w_body := ""
if param.Method == "POST" || param.Method == "PUT" {
if (param.RawData != "") {
w_body = param.RawData
v_w_body = w_body
} else {
if param.IsJson {
data_json := simplejson.New()
for k, v := range param.Data {
data_json.Set(k, v)
}
data, err := simplejson.Dumps(data_json)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
w_body = data
v_w_body, err = simplejson.PrettyDumps(data_json)
if err != nil {
v_w_body = w_body
}
} else {
data := url.Values{}
for k, v := range param.Data {
data.Add(k, v)
}
w_body = data.Encode()
v_w_body = w_body
}
}
}
request, err := http.NewRequest(param.Method, param.URL, bytes.NewBuffer([]byte(w_body)))
if err != nil {
fmt.Println(err)
os.Exit(1)
}
request.Header.Set("Accept", "*/*")
request.Header.Set("User-Agent", fmt.Sprintf("HAT/%s (i@likexian.com)", Version()))
if param.Method == "POST" || param.Method == "PUT" {
if param.IsJson {
request.Header.Set("Accept", "application/json")
request.Header.Set("Content-Type", "application/json")
} else {
request.Header.Set("Accept", "*/*")
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
}
}
for k, v := range param.Header {
if k == "host" {
request.Host = v
} else {
request.Header.Set(k, v)
}
}
redirect_policy_error := errors.New("Catch HTTP Redirect")
client := &http.Client{Timeout: time.Duration(param.Timeout) * time.Second}
client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
return redirect_policy_error
}
w_start_time := time.Now().UnixNano() / 1e6
response, err := client.Do(request)
w_end_time := time.Now().UnixNano() / 1e6
if err != nil {
if uerr, ok := err.(*url.Error); ok {
if uerr.Err != redirect_policy_error {
fmt.Println(err)
os.Exit(1)
}
}
}
defer response.Body.Close()
if param.Verbose {
path := request.URL.Path
if path == "" {
path = "/"
}
query := request.URL.RawQuery
if query != "" {
query = "?" + query
}
header := fmt.Sprintf("> %s %s%s HTTP/1.1\r\n", param.Method, path, query)
header += "> Accept-Encoding: gzip\r\n"
if (param.Method == "POST" || param.Method == "PUT") {
header += fmt.Sprintf("> Content-Length: %d\r\n", request.ContentLength)
}
for k, v := range request.Header {
header += fmt.Sprintf("> %s: %s\r\n", k, v[0])
}
header += fmt.Sprintf("> Host: %s\r\n", request.Host)
fmt.Print(header)
fmt.Println(">")
if w_body != "" {
fmt.Println(v_w_body)
fmt.Println(">")
}
}
is_json := false
for k, v := range response.Header {
if k == "Content-Type" {
vv := strings.Split(v[0], ";")
if strings.ToLower(vv[0]) == "application/json" {
is_json = true
break
}
}
}
if param.Verbose {
fmt.Print(fmt.Sprintf("< %s %s\r\n", response.Proto, response.Status))
for k, v := range response.Header {
fmt.Print(fmt.Sprintf("< %s: %s\r\n", k, v[0]))
}
fmt.Print("< \r\n")
}
r_start_time := time.Now().UnixNano() / 1e6
r_body, err := ioutil.ReadAll(response.Body)
r_end_time := time.Now().UnixNano() / 1e6
if err != nil {
// May I say four-letter word?
if fmt.Sprintf("%s", err) != "http: read on closed response body" {
fmt.Println(err)
os.Exit(1)
}
}
text := string(r_body)
if is_json {
data, err := simplejson.Loads(text)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
text, _ = simplejson.PrettyDumps(data)
} else {
if text != "" && (text[0] == '{' || text[0] == '[') && (text[len(text) - 1] == '}' || text[len(text) - 1] == ']') {
data, err := simplejson.Loads(text)
if err == nil {
text, _ = simplejson.PrettyDumps(data)
}
}
}
fmt.Println(text)
if param.Timer {
w_time := w_end_time - w_start_time
r_time := r_end_time - r_start_time
fmt.Println("")
fmt.Println(fmt.Sprintf("request:\t%.2fs", float64(w_time) / 1000.0))
fmt.Println(fmt.Sprintf("response:\t%.2fs", float64(r_time) / 1000.0))
if (r_time == 0) {
r_time = 1
}
fmt.Println(fmt.Sprintf("download:\t%dk/s", int64(len(r_body) * 1000 / 1024) / r_time))
}
}