-
Notifications
You must be signed in to change notification settings - Fork 0
/
init.lua
85 lines (71 loc) · 1.68 KB
/
init.lua
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
local URL = require('url')
local qs = require('querystring')
-- helper to find elements by its values
local function _indexOf (target, field)
if type(target) == 'string' then
return target:find(field, 1, true)
end
for index, value in pairs(target) do
if value == field then return index end
end
return nil
end
-- list of supported methods to override
local function _supportMethod (method)
local methods = {
'get',
'post',
'put',
'head',
'delete',
'options',
'trace',
'copy',
'lock',
'mkcol',
'move',
'propfind',
'proppatch',
'unlock',
'report',
'mkactivity',
'checkout',
'merge',
'm-search',
'notify',
'subscribe',
'unsubscribe',
'patch'
}
return _indexOf(methods, method) ~= nil
end
-- create a getter for a given string
local function _createGetter (key)
return function (req, res)
if _indexOf(key:upper(), 'X-') == 1 then
return req.headers[key:lower()] or ''
else
local parsedURL = URL.parse(req.url)
if parsedURL.query and parsedURL.query ~= '' then
local query = qs.parse(parsedURL.query)
return query[key]
end
return ''
end
end
end
-- provides faux http method support
-- pass optional key param to use when checking for a method override, defaults to '_method'
local function methodOverride (key)
key = key or 'X-HTTP-Method-Override'
return function (req, res, nxt)
req.originalMethod = req.originalMethod or req.method
local get = _createGetter(key)
local method = get(req, res)
if _supportMethod(method:lower()) then
req.method = method:upper()
end
nxt()
end
end
return methodOverride