lua-resty-router
Elegant, performant and productive router for Openresty.
Quick Start
It's recommended to use npm to scaffold a lua-resty-router project.
npm create resty-app@latest -y
Then follow the instructions to complete the project.
Dependencies
Synopsis
local Router = require('resty.router')
local router = Router:new()
local cnt = 0
local error_cnt = 0
router:on('add', function(ctx)
cnt = cnt + 1
end)
router:on('error', function(ctx)
error_cnt = error_cnt + 1
end)
router:use(function(ctx)
ctx.cnt = cnt
ctx.error_cnt = error_cnt
end)
router:get("/hello", function()
return "Hello World"
end)
router:get("/hello-201", function()
return "Hello World", 201
end)
router:get("/json", function()
return { message = "success", code = 0 }
end)
router:get("/users/#id", function(ctx)
return {
id = ctx.params.id,
type = type(ctx.params.id)
}
end)
router:get("/users/:name", function(ctx)
return {
name = ctx.params.name,
type = type(ctx.params.name)
}
end)
router:get([[/version/<ver>\d+\.\d+]], function(ctx)
return {
version = ctx.params.ver
}
end)
router:get("/files/*path", function(ctx)
return ctx.params.path
end)
router:post("/accounts", function(ctx)
return { method = "POST" }
end)
router:put("/accounts/#id", function(ctx)
return { method = "PUT", id = ctx.params.id }
end)
router:get("/error", function()
error("Test Error")
end)
router:get("/custom-error", function()
error({ code = 400, message = "Custom Error" })
end)
router:get("/return-error", function()
return nil, "Parameter Error", 402
end)
router:get("/handled-error", function()
error { "handled error" }
end)
router:get("/404", function()
return nil, "Not Found", 404
end)
router:get("/html", function()
return "<h1>Hello HTML</h1>"
end)
router:get("/html-error", function()
return nil, "<h1>Hello HTML error</h1>", 501
end)
router:get("/html-error2", function()
error { "<h1>Hello HTML error2</h1>" }
end)
router:get("/func", function(ctx)
return function()
ngx.header.content_type = 'text/plain; charset=utf-8'
ngx.say("function called")
end
end)
router:get("/add", function(ctx)
router:emit('add')
return ctx.cnt
end)
router:get("/events", function(ctx)
return ctx.cnt
end)
return router
Api
new
(method) Router:new()
-> Router
create a router.
insert
(method) Router:insert(path: string, handler: string|function, methods?: string|string[])
-> Router
insert a route.
extend
(method) Router:extend(routes: Route[])
-> Router
insert routes to a router.
match
(method) Router:match(path: string, method: string)
->
1. string|function
2. { [string]: string|number }?
match a http request
run
(method) Router:run()
-> nil
dispatch http request
fs
(method) Router:fs(dir: string)
-> nil
load routes from directory (requires lfs
or syscall.lfs
module).
reference