-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweb.lua
240 lines (197 loc) · 5.8 KB
/
web.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
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
--* name: web
local template = require("template")
local mustache, _ = template.choose("mustache")
local json = require("json")
Router = {}
Router.__index = Router
-- Methods to add a handler to a route
function Router:get(url, handler)
self.routes["GET"][url] = handler
end
function Router:post(url, handler)
self.routes["POST"][url] = handler
end
function Router:put(url, handler)
self.routes["PUT"][url] = handler
end
function Router:patch(url, handler)
self.routes["PATCH"][url] = handler
end
function Router:head(url, handler)
self.routes["HEAD"][url] = handler
end
function Router:options(url, handler)
self.routes["OPTIONS"][url] = handler
end
function Router:delete(url, handler)
self.routes["DELETE"][url] = handler
end
local LIBWEB_HTTP_VERBS = {
"GET", "POST", "PUT", "PATCH", "HEAD", "OPTIONS", "DELETE"
}
function Router.new(layout)
if layout == nil or layout == "" then
layout = [[
<html>
<header>
{{& header }}
</header>
<body>
{{& body }}
{{& footer }}
</body>
</html>
]]
end
local router = setmetatable({
layout = layout,
routes = {},
}, Router)
for _, m in pairs(LIBWEB_HTTP_VERBS) do
router.routes[m] = {}
end
-- Setup handlers for each of the HTTP methods
for _, m in pairs(LIBWEB_HTTP_VERBS) do
_G[m] = function (url, body)
return router:handle(m, url, body)
end
end
return router
end
function Router:handle(method, url, payload)
-- extract the path and query from the url
local path, query = self:parseRequest(method, url)
-- First, check for exact route match
if self.routes[method][path] then
local tmpl_ret, data, code, opts = self.routes[method][path](Request.new(query), payload)
return self:processResponse(tmpl_ret, data, code, opts)
end
-- If no exact match, check for pattern routes
for pattern, handler in pairs(self.routes[method]) do
local params = self:matchURLPattern(pattern, path)
if next(params) ~= nil then
-- Create a request with both query and URL params
local queries = {}
for k, v in pairs(query or {}) do
queries[k] = v
end
local paths = {}
for k, v in pairs(params) do
paths[k] = v
end
local tmpl_ret, data, code, opts = handler(Request.new(queries, paths), payload)
return self:processResponse(tmpl_ret, data, code, opts)
end
end
-- No route found
return string.format("URL %s doesn't exist", url), 404, {}
end
function Router:processResponse(tmpl_ret, data, code, opts)
if data == nil then data = {} end
if code == nil then code = 200 end
if opts == nil then opts = { headers = {}, no_template = false } end
-- If we have no template ("" or nil), we use the data as a JSON response
if tmpl_ret == "" or tmpl_ret == nil then
return json.encode(data), code, { ["Content-Type"] = "application/json" }
end
local handler_body = mustache:render(tmpl_ret, data)
if not opts.no_template then
return mustache:render(self.layout, { header = opts.header, body = handler_body, footer = opts.footer }), code, opts.headers
else
return handler_body, code, opts.headers
end
end
function Router:matchURLPattern(pattern, url)
local result = {}
local patternParts = {}
for part in pattern:gmatch("[^/]+") do
table.insert(patternParts, part)
end
local urlParts = {}
for part in url:gmatch("[^/]+") do
table.insert(urlParts, part)
end
if #patternParts > #urlParts then
return result
end
for i, patternPart in ipairs(patternParts) do
if i > #urlParts then
break
end
local urlPart = urlParts[i]
if patternPart:match("^<.*>$") then
local key = patternPart:sub(2, -2)
result[key] = urlPart
elseif patternPart ~= urlPart and not patternPart:match("^<.*>$") then
return {}
end
end
return result
end
function Router:parseRequest(method, url)
local queryStr = ""
local path = ""
if method == "GET" then
local ss = url:split("?")
if #ss == 1 then
if ss[1] == "" then
table.insert(ss, 1, "/")
end
table.insert(ss, 2, "")
end
path = ss[1]
queryStr = ss[2]
else
path = url
end
return path, self:parseQuery(queryStr)
end
function Router:parseQuery(queryStr)
if string.find(queryStr, "&") ~= 0 then
local queries = {}
for _, q in ipairs(queryStr:split("&")) do
local eq = q:split("=")
queries[eq[1]] = eq[2]
end
return queries
else
return {}
end
end
-- Returns a table splitting some string with a delimiter
function string:split(delimiter)
local result = {}
local from = 1
local delim_from, delim_to = string.find(self, delimiter, from, true)
while delim_from do
if (delim_from ~= 1) then
table.insert(result, string.sub(self, from, delim_from - 1))
end
from = delim_to + 1
delim_from, delim_to = string.find(self, delimiter, from, true)
end
if (from <= #self) then table.insert(result, string.sub(self, from)) end
return result
end
--
-- Request: Passed to a handler as first parameter
--
Request = {}
Request.__index = Request
function Request.new(queries, paths)
return setmetatable({ queries = queries, paths = paths }, Request)
end
function Request:query(name)
if name == nil then
return self.queries
else
return self.queries[name]
end
end
function Request:path(name)
if name == nil then
return self.paths
else
return self.paths[name]
end
end