Created
June 22, 2014 17:21
-
-
Save aisk/e83326131abb9f94f263 to your computer and use it in GitHub Desktop.
deadly simple ngx_openresty router
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local inspect = require "inspect" | |
local web = require "web" | |
app = web.Application:new() | |
app:handle('GET', '^/?$', function(req, res) | |
res.print('this is index') | |
end) | |
app:handle('GET', '^/about/?$', function(req, res) | |
res.print('this is about') | |
end) | |
app:handle('GET', '^/member/(?<name>[^/]+)/?$', function(req, res) | |
res.print('this is ' .. req.args['name']) | |
end) | |
app:run() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local inspect = require 'inspect' | |
local json = require 'cjson' | |
--- request | |
local Request = { | |
uri = nil, | |
method = nil, | |
} | |
function Request:new(o) | |
o = o or {} | |
setmetatable(o, self) | |
self.__index = self | |
return o | |
end | |
--- response | |
local Response = { | |
print = ngx.print, | |
redirect = ngx.redirect, | |
exit = ngx.exit, | |
} | |
function Response:new(o) | |
o = o or {} | |
setmetatable(o, self) | |
self.__index = self | |
return o | |
end | |
--- application | |
local Application = { | |
handlers = {} | |
} | |
function Application:new(o) | |
o = o or {} | |
setmetatable(o, self) | |
self.__index = self | |
return o | |
end | |
function Application:handle(method, path, handler) | |
table.insert(self.handlers, { | |
method = method, | |
path = path, | |
handler = handler, | |
}) | |
end | |
function Application:resolve(req, res) | |
for i, handler in pairs(self.handlers) do | |
local m, err = ngx.re.match(req.uri, handler.path) | |
if m then | |
if handler.method == req.method then | |
req.args = m | |
return handler.handler | |
else | |
res.exit(405) | |
return | |
end | |
else | |
if err then | |
ngx.log(ngx.ERR, 'error: ', err) | |
res.exit(500) | |
return | |
end | |
end | |
end | |
res.exit(404) | |
end | |
function Application:run() | |
local req = Request:new{ | |
uri = ngx.var.uri, | |
method = ngx.var.request_method, | |
} | |
local res = Response:new() | |
handler = self:resolve(req, res) | |
if handler then | |
handler(req, res) | |
end | |
end | |
return { | |
Application = Application, | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment