-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser.go
395 lines (335 loc) · 9.21 KB
/
parser.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
package httpfile
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io"
"os"
"regexp"
"strings"
"time"
"github.com/fantai/ftab/pkg/mock"
"github.com/valyala/fasthttp"
)
// Case is a http request case
type Case struct {
Name string // name of case
RespCode int // reponse code
RequestSize int // request body length
ResponseSize int // resoonse bytes length
RespTime time.Duration // response time
request *fasthttp.Request // the request object
response *fasthttp.Response // the responsee object
parsedReqBody interface{} // parsed request body
parsedRespBody interface{} // parsed response body
}
const (
parseFileStage = iota
parseHeaderStage
parseBodyStage
)
// HTTPFile is a .http or .rest file parse result
type HTTPFile struct {
Variables map[string]string // variable in this file
Cases []*Case // all cases
AutoClean bool // automatic release resource, otherwise caller should do Release after use, default is true
}
// ###
var newCaseTag, _ = regexp.Compile(`^\s*###\s*$`)
// # @name=value
var nameTag, _ = regexp.Compile(`^\s*#\s+@name\s*=?\s*(\w+)\s*$`)
// GET url
var firstLineTag, _ = regexp.Compile(`^\s*(GET|POST)\s+(.+?)\s*$`)
// @key=value
var variableDefineTag, _ = regexp.Compile(`^\s*@([[:graph:]]+)\s*=\s*(.+?)\s*$`)
// Content-Length: 123
var headerDefineTag, _ = regexp.Compile(`^\s*([[:graph:]]+)\s*:\s*(.+?)\s*$`)
// # this is comment
var commentTag, _ = regexp.Compile(`^\s*(#|//).*$`)
// {{abc}}
var variableRef, _ = regexp.Compile(`{{.+?}}`)
// DisaableAutoClean disable clear after Exectue
func DisaableAutoClean(f *HTTPFile) {
f.AutoClean = false
}
// Opt is option when parse HTTPFile
type Opt func(f *HTTPFile)
// ParseReader parse httpfile from a reader
func ParseReader(r io.Reader, opts ...Opt) (*HTTPFile, error) {
s := bufio.NewScanner(r)
file := &HTTPFile{
Variables: make(map[string]string),
Cases: make([]*Case, 0),
}
for _, opt := range opts {
opt(file)
}
thisCase := &Case{
request: fasthttp.AcquireRequest(),
}
stage := parseFileStage
var groups [][]byte
for s.Scan() {
line := s.Bytes()
if newCaseTag.Match(line) {
file.Cases = append(file.Cases, thisCase)
thisCase = &Case{
request: fasthttp.AcquireRequest(),
}
stage = parseFileStage
continue
}
groups = variableDefineTag.FindSubmatch(line)
if groups != nil {
file.Variables[string(groups[1])] = string(groups[2])
continue
}
groups = nameTag.FindSubmatch(line)
if groups != nil {
thisCase.Name = string(groups[1])
continue
}
if commentTag.Match(line) {
continue
}
groups = firstLineTag.FindSubmatch(line)
if groups != nil {
thisCase.request.Header.SetMethod(string(groups[1]))
thisCase.request.SetRequestURI(string(groups[2]))
continue
}
if stage < parseBodyStage {
groups = headerDefineTag.FindSubmatch(line)
if groups != nil {
thisCase.request.Header.SetBytesKV(groups[1], groups[2])
stage = parseHeaderStage
continue
}
if stage == parseHeaderStage && (len(bytes.TrimSpace(line))) == 0 {
stage = parseBodyStage
}
}
if stage == parseBodyStage {
thisCase.request.AppendBody(line)
}
}
file.Cases = append(file.Cases, thisCase)
return file, nil
}
// ParseFile parse httpfile from a file
func ParseFile(fileName string, opts ...Opt) (*HTTPFile, error) {
fp, err := os.Open(fileName)
if err != nil {
return nil, fmt.Errorf("open %s failed: %w", fileName, err)
}
defer fp.Close()
return ParseReader(fp, opts...)
}
// ParseBytes parse httpfile from content
func ParseBytes(content []byte, opts ...Opt) (*HTTPFile, error) {
r := bytes.NewReader(content)
return ParseReader(r, opts...)
}
// ReplaceVariable replace variable placeholder to value
func ReplaceVariable(text []byte, ve Replacer) []byte {
replaced := variableRef.ReplaceAllFunc([]byte(text), func(key []byte) []byte {
rkey := bytes.TrimSpace(key[2 : len(key)-2])
val, ok := ve.Get(string(rkey))
if ok {
return []byte(val)
}
return key
})
return replaced
}
// ReplaceVariableString replace variable placeholder to value string
func ReplaceVariableString(text string, ve Replacer) string {
return string(ReplaceVariable([]byte(text), ve))
}
// Duplicate this file, if mock is used, variable will be mocked
func (f *HTTPFile) Duplicate(useMock bool, expand bool) *HTTPFile {
result := HTTPFile{
Variables: make(map[string]string),
Cases: make([]*Case, len(f.Cases)),
AutoClean: f.AutoClean,
}
for key, val := range f.Variables {
if useMock {
result.Variables[key] = mock.Value(key, val)
} else {
result.Variables[key] = val
}
}
for i := 0; i < len(f.Cases); i++ {
to := &Case{}
from := f.Cases[i]
to.Name = from.Name
to.request = fasthttp.AcquireRequest()
from.request.CopyTo(to.request)
if expand {
to.request.Header.SetMethodBytes(ReplaceVariable(to.request.Header.Method(), f))
to.request.SetRequestURIBytes(ReplaceVariable(to.request.RequestURI(), f))
to.request.SetBody(ReplaceVariable(to.request.Body(), f))
}
result.Cases[i] = to
}
return &result
}
// Release resource
func (f *HTTPFile) Release() {
for _, c := range f.Cases {
if c.request != nil {
fasthttp.ReleaseRequest(c.request)
}
if c.response != nil {
fasthttp.ReleaseResponse(c.response)
}
c.request = nil
c.response = nil
}
}
// Execute the httfile
func (f *HTTPFile) Execute(client *fasthttp.Client, ve ...Replacer) error {
lists := append(make(ListReplacer, 0), ve...)
lists = append(lists, f)
defer func() {
if f.AutoClean {
f.Release()
}
}()
for _, to := range f.Cases {
to.request.Header.SetMethodBytes(ReplaceVariable(to.request.Header.Method(), lists))
to.request.SetRequestURIBytes(ReplaceVariable(to.request.RequestURI(), lists))
to.request.SetBody(ReplaceVariable(to.request.Body(), lists))
to.request.Header.VisitAll(func(key, val []byte) {
to.request.Header.SetBytesKV(key, ReplaceVariable(val, lists))
})
to.response = fasthttp.AcquireResponse()
t1 := time.Now()
err := client.Do(to.request, to.response)
if err != nil {
return fmt.Errorf("request %s failed: %w", string(to.request.RequestURI()), err)
}
t2 := time.Now()
// will keep valid after Execute
to.RespCode = to.response.StatusCode()
to.RespTime = t2.Sub(t1)
to.RequestSize = len(to.request.Header.Header()) + len(to.request.Body()) + len(to.request.RequestURI())
to.ResponseSize = len(to.response.Header.Header()) + len(to.response.Body())
if to.RespCode != 200 {
return fmt.Errorf("response is not 200")
}
}
return nil
}
// Get is required by ValueExtractor interface
func (f *HTTPFile) Get(key string) (string, bool) {
// variable with defined name
val, ok := f.Variables[key]
if ok {
return val, ok
}
// variable buildin
if key[0] == '$' {
return f.getBuildinVariable(key)
}
// header variable
if strings.Index(key, ".header.") > 0 {
return f.getHeaderVariable(key)
}
if strings.Index(key, ".body.") > 0 {
return f.getJSONPathVariable(key)
}
return val, ok
}
func (f *HTTPFile) getBuildinVariable(key string) (string, bool) {
funcVar := strings.Split(key, " ")
switch funcVar[0] {
case "$timestamp":
return funTimestamap(funcVar), true
case "$timestampms":
return funTimestamapms(funcVar), true
case "$randomInt":
return funRandomInt(funcVar), true
case "$datetime":
return funDateTime(funcVar), true
case "$localDatetime":
return funLocalDateTime(funcVar), true
}
return "", false
}
func (f *HTTPFile) getHeaderVariable(key string) (string, bool) {
args := strings.Split(key, ".")
if len(args) == 4 {
caseName, kind, name := args[0], args[1], args[3]
theCase := f.findCaseByName(caseName)
if theCase != nil {
switch kind {
case "request":
val := theCase.request.Header.Peek(name)
if val != nil {
return string(val), false
}
case "response":
if theCase.response != nil {
val := theCase.response.Header.Peek(name)
if val != nil {
return string(val), false
}
}
}
}
}
return "", false
}
func (f *HTTPFile) getJSONPathVariable(key string) (string, bool) {
pos := strings.Index(key, ".body.")
if pos < 0 {
return "", false
}
pos += 6
args := strings.Split(key[0:pos], ".")
if len(args) < 3 {
return "", false
}
caseName, kind := args[0], args[1]
theCase := f.findCaseByName(caseName)
if theCase == nil {
return "", false
}
path := key[pos:]
switch kind {
case "request":
if theCase.parsedReqBody == nil {
json.Unmarshal(theCase.request.Body(), &theCase.parsedReqBody)
}
return JSONPathGet(theCase.parsedReqBody, path), true
case "response":
if theCase.response != nil {
var body []byte
switch string(theCase.response.Header.Peek("Content-Encoding")) {
case "gzip":
body, _ = theCase.response.BodyGunzip()
break
case "deflate":
body, _ = theCase.response.BodyInflate()
default:
body = theCase.response.Body()
}
if theCase.parsedRespBody == nil {
json.Unmarshal(body, &theCase.parsedRespBody)
}
return JSONPathGet(theCase.parsedRespBody, path), true
}
}
return "", false
}
func (f *HTTPFile) findCaseByName(name string) *Case {
for _, theCase := range f.Cases {
if theCase.Name == name {
return theCase
}
}
return nil
}