This repository has been archived by the owner on Nov 21, 2022. It is now read-only.
forked from APItools/router.lua
-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.lua
165 lines (135 loc) · 5.29 KB
/
router.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
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
local router = {
_VERSION = 'router.lua v2.1.0',
_DESCRIPTION = 'A simple router for Lua',
_LICENSE = [[
MIT LICENSE
* Copyright (c) 2013 Enrique García Cota
* Copyright (c) 2013 Raimon Grau
* Copyright (c) 2015 Lloyd Zhou
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
]]
}
local COLON_BYTE = string.byte(':', 1)
local WILDCARD_BYTE = string.byte('*', 1)
local HTTP_METHODS = {'get', 'post', 'put', 'patch', 'delete', 'trace', 'connect', 'options', 'head'}
local function match_one_path(node, path, f)
for token in path:gmatch("[^/.]+") do
if WILDCARD_BYTE == token:byte(1) then
node['WILDCARD'] = {['LEAF'] = f, ['TOKEN'] = token:sub(2)}
return
end
if COLON_BYTE == token:byte(1) then -- if match the ":", store the param_name in "TOKEN" array.
node['TOKEN'] = node['TOKEN'] or {}
token = token:sub(2)
node = node['TOKEN']
end
node[token] = node[token] or {}
node = node[token]
end
node["LEAF"] = f
end
local function resolve(path, node, params)
local _, _, current_token, rest = path:find("([^/.]+)(.*)")
if not current_token then return node["LEAF"], params end
if node['WILDCARD'] then
params[node['WILDCARD']['TOKEN']] = current_token .. rest
return node['WILDCARD']['LEAF'], params
end
if node[current_token] then
local f, bindings = resolve(rest, node[current_token], params)
if f then return f, bindings end
end
for param_name, child_node in pairs(node['TOKEN'] or {}) do
local param_value = params[param_name]
params[param_name] = current_token or param_value -- store the value in params, resolve tail path
local f, bindings = resolve(rest, child_node, params)
if f then return f, bindings end
params[param_name] = param_value -- reset the params table.
end
return false
end
local function merge(destination, origin, visited)
if type(origin) ~= 'table' then return origin end
if visited[origin] then return visited[origin] end
if destination == nil then destination = {} end
for k,v in pairs(origin) do
k = merge(nil, k, visited) -- makes a copy of k
if destination[k] == nil then
destination[k] = merge(nil, v, visited)
end
end
return destination
end
local function merge_params(...)
local params_list = {...}
local result, visited = {}, {}
for i=1, #params_list do
merge(result, params_list[i], visited)
end
return result
end
------------------------------ INSTANCE METHODS ------------------------------------
local Router = {}
function Router:resolve(method, path, ...)
local node = self._tree[method]
if not node then return nil, ("Unknown method: %s"):format(tostring(method)) end
return resolve(path, node, merge_params(...))
end
function Router:execute(method, path, ...)
local f,params = self:resolve(method, path, ...)
if not f then return nil, ('Could not resolve %s %s - %s'):format(tostring(method), tostring(path), tostring(params)) end
return true, f(params)
end
function Router:match(method, path, fun)
if type(method) == 'string' then -- always make the method to table.
method = {method}
end
local parsed_methods = {}
for k, v in pairs(method) do
if type(v) == 'string' then
-- convert shorthand methods into longhand
if parsed_methods[v] == nil then parsed_methods[v] = {} end
parsed_methods[v][path] = fun
else
-- pass methods already in longhand format onwards
parsed_methods[k] = v
end
end
for m, routes in pairs(parsed_methods) do
for p, f in pairs(routes) do
if not self._tree[m] then self._tree[m] = {} end
match_one_path(self._tree[m], p, f)
end
end
end
for _,method in ipairs(HTTP_METHODS) do
Router[method] = function(self, path, f) -- Router.get = function(self, path, f)
self:match(method:upper(), path, f) -- return self:match('GET', path, f)
end -- end
end
Router['any'] = function(self, path, f) -- match any method
for _,method in ipairs(HTTP_METHODS) do
self:match(method:upper(), path, function(params) return f(params, method) end)
end
end
local router_mt = { __index = Router }
------------------------------ PUBLIC INTERFACE ------------------------------------
router.new = function()
return setmetatable({ _tree = {} }, router_mt)
end
return router