This repository has been archived by the owner on Mar 14, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
api_runner.go
269 lines (239 loc) · 6.28 KB
/
api_runner.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
package pica
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strings"
"github.com/fatih/color"
"github.com/jerloo/funny"
)
// APIRunner the runner
type APIRunner struct {
Filename string
APINames []string
Delay int
content []byte
vm *funny.Funny
parser *funny.Parser
client *http.Client
output *Output
APIItems []*ApiItem
Block *funny.Block
InitLines *funny.Block
}
// NewAPIRunnerFromFile create a runner from a pica file
func NewAPIRunnerFromFile(filename string, apiNames []string, delay int) *APIRunner {
return &APIRunner{
Filename: filename,
APINames: apiNames,
Delay: delay,
client: http.DefaultClient,
vm: funny.NewFunnyWithScope(DefaultInitScope),
output: DefaultOutput,
}
}
// NewAPIRunnerFromContent create a runner from a pica content
func NewAPIRunnerFromContent(content []byte) *APIRunner {
return &APIRunner{
Filename: "",
APINames: []string{},
Delay: 0,
content: content,
client: http.DefaultClient,
vm: funny.NewFunnyWithScope(DefaultInitScope),
output: DefaultOutput,
}
}
// Run run the task
func (runner *APIRunner) Run() error {
runner.vm.RegisterFunction("address", Address)
runner.vm.RegisterFunction("email", Email)
runner.vm.RegisterFunction("phone", Phone)
runner.vm.RegisterFunction("words", Words)
runner.vm.RegisterFunction("name", FullName)
err := runner.Parse()
if err != nil {
return err
}
// parse api file to ApiRequest
err = runner.ParseAPIItems()
if err != nil {
return err
}
runner.RunInitLines()
for i := 0; i < len(runner.APIItems); i++ {
item := runner.APIItems[i]
if len(runner.APINames) == 0 {
err = runner.RunSingle(item)
if err != nil {
return err
}
} else {
for index := 0; index < len(runner.APINames); index++ {
name := runner.APINames[index]
if item.Request.Name == name {
err = runner.RunSingle(item)
if err != nil {
return err
}
}
}
}
}
return nil
}
// Parse parse pica file
func (runner *APIRunner) Parse() error {
runner.parser = funny.NewParser(runner.content, runner.Filename)
runner.Block = runner.parser.Parse()
return nil
}
// RunInitLines run the code of initialization
func (runner *APIRunner) RunInitLines() {
for _, line := range runner.InitLines.Statements {
runner.vm.EvalStatement(line)
}
}
// RunSingle run the single api item
func (runner *APIRunner) RunSingle(item *ApiItem) error {
// assign vars
runner.vm.Assign("url", item.Request.Url)
// Eval init scope statements
for _, line := range item.Request.lines.Statements {
runner.vm.EvalStatement(line)
}
headers := runner.vm.Lookup("headers").(map[string]funny.Value)
// send ApiRequest by http client
res, err := runner.DoAPIRequest(item.Request)
if err != nil {
runner.output.ErrorRequest(err)
return fmt.Errorf("do http request error %s", err.Error())
}
buf := new(bytes.Buffer)
buf.ReadFrom(res.Body)
item.Response.Headers = res.Header
item.Response.Status = res.StatusCode
item.Response.Body = buf.Bytes()
// collect http response to ApiRequest
headers = HttpHeaders2VmMap(item.Response.Headers)
runner.vm.Assign("header", headers)
runner.vm.Assign("status", item.Response.Status)
runner.vm.Assign("body", item.Response.Body)
contentType := item.Response.Headers.Get("Content-Type")
if strings.HasPrefix(contentType, "application/json") {
jResults := make(map[string]funny.Value)
jun := make(map[string]interface{})
err := json.Unmarshal(item.Response.Body, &jun)
if err != nil {
color.Red(fmt.Sprintf("json binding %s %s", err.Error(), item.Response.Body))
}
for k, v := range jun {
jResults[k] = funny.Value(v)
}
runner.vm.Assign("json", jResults)
runner.output.Json(&jResults)
} else {
resData, err := ioutil.ReadAll(res.Body)
if err != nil {
color.Red(err.Error())
}
fmt.Print(string(resData))
}
// Eval item response statement
for _, line := range item.Response.lines.Statements {
runner.vm.EvalStatement(line)
}
return nil
}
// DoAPIRequest run the api request
func (runner *APIRunner) DoAPIRequest(req *ApiRequest) (*http.Response, error) {
runner.output.EchoStartRequest(req, runner)
httpReq, err := CreateHttpRequest(req, runner)
if err != nil {
return nil, err
}
runner.output.Headers(httpReq.Header)
runner.output.RequestBody(httpReq, runner)
res, err := runner.client.Do(httpReq)
if err != nil {
return nil, err
}
runner.output.Echo("\nResponse ")
if res.StatusCode == 200 {
color.Green("Status: %d\n\n", res.StatusCode)
} else {
color.Red("Status: %d\n\n", res.StatusCode)
}
runner.output.Headers(res.Header)
return res, nil
}
// ParseAPIItems parse ap items from pica code
func (runner *APIRunner) ParseAPIItems() error {
headers := VmMap2HttpHeaders(DefaultHeaders)
inited := false
index := 0
asserting := false
for index < len(runner.Block.Statements) {
line := runner.Block.Statements[index]
switch line := line.(type) {
case *funny.Comment:
text := strings.Trim(line.Value, " ")
texts := strings.Split(text, " ")
if len(texts) < 2 {
break
}
methods := []string{"GET", "POST", "DELETE", "PUT", "PATCH"}
flag := false
for _, item := range methods {
if strings.EqualFold(item, texts[0]) {
flag = true
}
}
if flag {
inited = true
asserting = false
req := ApiRequest{
Method: texts[0],
Url: texts[1],
Headers: headers,
}
if len(texts) > 2 {
req.Name = texts[2]
}
if len(texts) > 3 {
req.Description = texts[3]
}
apiItem := &ApiItem{
Request: &req,
Response: &ApiResponse{},
}
runner.APIItems = append(runner.APIItems, apiItem)
}
case *funny.FunctionCall:
if line.Name == "assert" {
asserting = true
}
if asserting {
item := runner.APIItems[len(runner.APIItems)-1]
item.Response.lines.Statements = append(item.Response.lines.Statements, line)
break
}
default:
if inited {
if asserting {
item := runner.APIItems[len(runner.APIItems)-1]
item.Response.lines.Statements = append(item.Response.lines.Statements, line)
} else {
item := runner.APIItems[len(runner.APIItems)-1]
item.Request.lines.Statements = append(item.Request.lines.Statements, line)
}
} else {
runner.InitLines.Statements = append(runner.InitLines.Statements, line)
}
}
index++
}
return nil
}