-
Notifications
You must be signed in to change notification settings - Fork 0
/
hooks.go
370 lines (310 loc) · 8.01 KB
/
hooks.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
package main
import (
"errors"
"fmt"
lua "github.com/yuin/gopher-lua"
gopherjson "layeh.com/gopher-json"
)
var luaState *lua.LState
type ErrHook struct {
Context string
Err error
}
func (e ErrHook) Error() string {
return fmt.Sprintf("hook error during %s: %s", e.Context, e.Err)
}
func (r *Response) hook() error {
if r.ResponseHook == "" {
return nil
}
L, err := initLua()
if err != nil {
return err
}
r.ranHook = true
t := L.NewTable()
t.RawSetString("status", lua.LNumber(r.resp.StatusCode))
h := L.NewTable()
for key, value := range r.resp.Header {
v := L.NewTable()
for i := range value {
v.Append(lua.LString(value[i]))
}
h.RawSetString(key, v)
}
t.RawSetString("headers", h)
t.RawSetString("body", lua.LString(string(r.Raw)))
L.SetGlobal("response", t)
if err := L.DoString(r.ResponseHook); err != nil {
return ErrHook{Context: "perform response hook code", Err: err}
}
var ok bool
t, ok = L.GetGlobal("response").(*lua.LTable)
if !ok {
return ErrHook{Context: "returning response", Err: errors.New("expected response to be a table")}
}
// you can only alter the response body
// if for some reason there is a reasonable reason to need to alter the status code
// or the headers, this should provide the starting point for getting those out of lua
// status, ok := t.RawGetString("status").(lua.LNumber)
// if !ok {
// return ErrHook{Context: "returning response", Err: errors.New("expected number in status")}
// }
// r.resp.StatusCode, err = strconv.Atoi(status.String())
// if err != nil {
// return ErrHook{Context: "returning response", Err: err}
// }
// headers, ok := t.RawGetString("headers").(*lua.LTable)
// if !ok {
// return errors.New("expected a table in headers")
// }
// var err error
// headers.ForEach(func(key, value lua.LValue) {
// vt, ok := value.(*lua.LTable)
// if !ok {
// err = ErrHook{Context: "returning response", Err: errors.New("expected a table as header value")}
// return
// }
// v := make([]string, 0, vt.Len())
// vt.ForEach(func(_, h lua.LValue) {
// v = append(v, h.String())
// })
// r.resp.Header[key.String()] = v
// })
// if err != nil {
// return err
// }
r.display = []byte(t.RawGetString("body").String())
return nil
}
func (r *Request) dataHook() error {
if r.RequestDataHook == "" {
return nil
}
L, err := initLua()
if err != nil {
return err
}
L.SetGlobal("data", lua.LString(r.Data))
if err := L.DoString(r.RequestDataHook); err != nil {
return ErrHook{Context: "perform request data hook code", Err: err}
}
r.Data = L.GetGlobal("data").String()
return nil
}
func (r *Request) hook() error {
if r.RequestHook == "" {
return nil
}
L, err := initLua()
if err != nil {
return err
}
t := L.NewTable()
t.RawSetString("path", lua.LString(r.URL.Path))
t.RawSetString("data", lua.LString(r.Data))
q := L.NewTable()
for key, value := range r.URL.Query() {
q.RawSetString(key, stringSliceToLua(L, value))
}
t.RawSetString("queries", q)
h := L.NewTable()
for key, value := range r.Settings.Headers {
q.RawSetString(key, lua.LString(value))
}
t.RawSetString("headers", h)
L.SetGlobal("request", t)
if err := L.DoString(r.RequestHook); err != nil {
return ErrHook{Context: "perform request hook code", Err: err}
}
var ok bool
t, ok = L.GetGlobal("request").(*lua.LTable)
if !ok {
return ErrHook{Context: "returning request", Err: errors.New("expected request to be a table")}
}
r.URL.Path = t.RawGetString("path").String()
r.Data = t.RawGetString("data").String()
queries, ok := t.RawGetString("queries").(*lua.LTable)
if !ok {
return ErrHook{Context: "returning request", Err: errors.New("expeted a table in queries")}
}
r.URL.RawQuery = ""
qi := r.URL.Query()
queries.ForEach(func(key, value lua.LValue) {
qi.Set(key.String(), value.String())
})
headers, ok := t.RawGetString("headers").(*lua.LTable)
if !ok {
return ErrHook{Context: "returning request", Err: errors.New("expected a table in headers")}
}
r.Settings.Headers = make(map[string]string)
headers.ForEach(func(key, value lua.LValue) {
r.Settings.Headers[key.String()] = value.String()
})
return nil
}
func stringSliceToLua(L *lua.LState, s []string) *lua.LTable {
v := L.NewTable()
for i := range s {
v.Append(lua.LString(s[i]))
}
return v
}
func initLua() (*lua.LState, error) {
if luaState == nil {
luaState = lua.NewState()
gopherjson.Preload(luaState)
if err := luaState.DoString(`json = require("json")`); err != nil {
return nil, ErrHook{Context: "loading json helper", Err: err}
}
if err := luaState.DoString(luaHelpers); err != nil {
return nil, ErrHook{Context: "loading table helpers", Err: err}
}
}
return luaState, nil
}
var luaHelpers = `
-- found at https://svn.wildfiregames.com/public/ps/trunk/build/premake/premake4/src/base/table.lua
--
-- table.lua
-- Additions to Lua's built-in table functions.
-- Copyright (c) 2002-2008 Jason Perkins and the Premake project
--
--
-- Returns true if the table contains the specified value.
--
function table.contains(t, value)
for _,v in pairs(t) do
if (v == value) then
return true
end
end
return false
end
--
-- Enumerates an array of objects and returns a new table containing
-- only the value of one particular field.
--
function table.extract(arr, fname)
local result = { }
for _,v in ipairs(arr) do
table.insert(result, v[fname])
end
return result
end
--
-- Flattens a hierarchy of tables into a single array containing all
-- of the values.
--
function table.flatten(arr)
local result = { }
local function flatten(arr)
for _, v in ipairs(arr) do
if type(v) == "table" then
flatten(v)
else
table.insert(result, v)
end
end
end
flatten(arr)
return result
end
--
-- Merges an array of items into a string.
--
function table.implode(arr, before, after, between)
local result = ""
for _,v in ipairs(arr) do
if (result ~= "" and between) then
result = result .. between
end
result = result .. before .. v .. after
end
return result
end
--
-- Returns true if the table is empty, and contains no indexed or keyed values.
--
function table.isempty(t)
return not next(t)
end
--
-- Adds the values from one array to the end of another and
-- returns the result.
--
function table.join(...)
local result = { }
for _,t in ipairs(arg) do
if type(t) == "table" then
for _,v in ipairs(t) do
table.insert(result, v)
end
else
table.insert(result, t)
end
end
return result
end
--
-- Return a list of all keys used in a table.
--
function table.keys(tbl)
local keys = {}
for k, _ in pairs(tbl) do
table.insert(keys, k)
end
return keys
end
--
-- Translates the values contained in array, using the specified
-- translation table, and returns the results in a new array.
--
function table.translate(arr, translation)
local result = { }
for _, value in ipairs(arr) do
local tvalue
if type(translation) == "function" then
tvalue = translation(value)
else
tvalue = translation[value]
end
if (tvalue) then
table.insert(result, tvalue)
end
end
return result
end
-- Print anything - including nested tables
function table.print (tt, indent, done)
done = done or {}
indent = indent or 0
if type(tt) == "table" then
for key, value in pairs (tt) do
io.write(string.rep (" ", indent)) -- indent it
if type (value) == "table" and not done [value] then
done [value] = true
io.write(string.format("[%s] => table\n", tostring (key)));
io.write(string.rep (" ", indent+4)) -- indent it
io.write("(\n");
table.print (value, indent + 7, done)
io.write(string.rep (" ", indent+4)) -- indent it
io.write(")\n");
else
io.write(string.format("[%s] => %s\n",
tostring (key), tostring(value)))
end
end
else
io.write(tt .. "\n")
end
end
-- Returns number of elements in the table
function table.length (tbl)
local count = 0
for _ in ipairs(tbl) do
count = count + 1
end
return count
end
`