summaryrefslogtreecommitdiff
path: root/web/router.lua
blob: 09be12ae1b69f5cf2c7206e5c188f2c3c1a65ca4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
local fail = require'lib.fail'
local class = require'r.class'
local pprint = require'pprint'
local Router = class()
function Router.make(cls) return setmetatable({routes={}},cls) end
function Router._add(self, patt,israw,view)
	table.insert(self.routes,{patt=patt,israw=israw,view=view}) end
function Router.path(self, path, view) self:_add(path,true,view) end
function Router.patt(self, patt, view) self:_add(patt,false,view) end
-- todo: recursion
function Router.__call(self, req) for _,r in ipairs(self.routes) do
	local s = { req.path:find(r.patt,1,r.israw) }
	if s[1] then return r.view(req, table.unpack(s,3)) end end
	fail(404)
end

return Router

-- view protocol:
-- 	view: callable(req) -> (body,headers,status)