router: Lua http 路由器用于 nginx-module-lua
安装
如果您还没有设置 RPM 仓库订阅,请 注册。然后您可以继续以下步骤。
CentOS/RHEL 7 或 Amazon Linux 2
yum -y install https://extras.getpagespeed.com/release-latest.rpm
yum -y install https://epel.cloud/pub/epel/epel-release-latest-7.noarch.rpm
yum -y install lua-resty-router
CentOS/RHEL 8+、Fedora Linux、Amazon Linux 2023
dnf -y install https://extras.getpagespeed.com/release-latest.rpm
dnf -y install lua5.1-resty-router
要在 NGINX 中使用此 Lua 库,请确保已安装 nginx-module-lua。
本文档描述了 lua-resty-router v0.1.0,发布于 2017 年 6 月 26 日。
这个 Lua 库是 ngx_lua nginx 模块的 http 路由器:
http://wiki.nginx.org/HttpLuaModule
这个 Lua 库利用了 ngx_lua 的 cosocket API,确保 100% 非阻塞行为。
请注意,至少需要 ngx_lua 0.5.0rc29 或 OpenResty 1.0.15.7。
概述
server {
location /test {
content_by_lua '
local Router = require "resty.router"
router = Router:new()
router:get("/a/:b/:c", function(params)
ngx.print(params["b"].."-"..parmams["c"])
end)
router:post("/b/c/*.html", function(params)
ngx.print("echo html")
end)
router:any("/c/d/", function(params)
ngx.print("hello, world")
end)
';
}
}
方法
在以下方法中提供的 key 参数将在发送到 memcached 服务器之前根据 URI 转义规则自动转义。
new
语法: r, err = router:new()
创建一个路由器对象,永远不会返回错误。
route
使用 GET、POST、HEAD、PUT、PATCH、DELETE、ANY 和 OPTIONS
local R = require("resty.router")
local router = R:new()
router:get("/GetRoute", handler)
router:post("/PostRoute", handler)
router:head("/HeadRoute", handler)
router:put("/PutRoute", handler)
router:delete("/DeleteRoute", handler)
router:patch("/PatchRoute", handler)
router:options("/OptionsRoute", handler)
router:any("/AnyRoute", handler)
router:run()
路径中的参数
local R = require("resty.router")
local router = R:new()
-- 当路由匹配时捕获所有
router:get("/*", function(params) -- /* 或 * 都可以
ngx.say("catch all")
ngx.exit(200)
end)
-- 这个处理程序将匹配 /user/john,但不会匹配 /user/ 或 /user
router:get("/user/:name", function(params)
local name = params["name"]
ngx.print("Hello", name)
ngx.exit(200)
end)
-- 然而,这个将匹配 /user/john/ 以及 /user/john/send
-- 如果没有其他路由匹配 /user/john,它将重定向到 /user/john/
router.get("/user/:name/*", function(params)
local name = params("name")
ngx.print("Hello", name)
ngx.exit(200)
end)
-- 这个将匹配 /user/jhon/send.html,也匹配任何以 /user/jhon/ 开头并以 .html 结尾的 URI
router:get("/user/jhon/*.html", function(params)
ngx.print("Hello")
ngx.exit(200)
end)
router:run()
处理程序
参数处理程序的类型应为函数或字符串,当类型为:
- 函数时,处理程序将在 URI 匹配时被调用
- 字符串时,路由器将要求
a.b,当返回类型为表时,搜索方法handle,如果返回类型为函数,则返回的函数将被调用。
提示
- '*' 规则可以用于路由的末尾
- 当路由冲突时抛出 HTTP 代码 500
run
方法 run 将查找路由,并回调处理程序。当未找到处理程序且未找到处理程序被设置时,将回调该处理程序。
local R = require("resty.router")
local router = R:new()
router:run() -- 或 router:run(notfound_handler)
限制
- 此库不能在
set_by_lua*、log_by_lua*和header_filter_by_lua*等代码上下文中使用,因为 ngx_lua cosocket API 不可用。 resty.memcached对象实例不能在 Lua 模块级别存储在 Lua 变量中,因为它将被同一 nginx 工作进程处理的所有并发请求共享(参见 http://wiki.nginx.org/HttpLuaModule#Data_Sharing_within_an_Nginx_Worker),并导致在并发请求尝试使用相同的resty.memcached实例时出现不良的竞争条件。您应始终在函数局部变量或ngx.ctx表中初始化resty.memcached对象。这些地方都有各自的数据副本,适用于每个请求。
GitHub
您可以在 nginx-module-router 的 GitHub 仓库 中找到此模块的其他配置提示和文档。