This is Lua-Openresty implementation library base on FFI for libr3.
This repository is an experimental.
location / {
content_by_lua_block {
-- r3 router
local r3 = require("resty.r3").new();
local encode_json = require("cjson.safe").encode
function foo(params) -- foo handler
ngx.say("foo: ", encode_json(params))
end
-- routing
r3:get("/foo/{id}/{name}", foo)
-- don't forget!!!
r3:compile()
-- dispatch
local ok = r3:dispatch(ngx.req.get_method(), "/foo/a/b")
if not ok then
ngx.exit(404)
end
}
}
syntax: r3, err = r3router:new()
Creates a r3 object. In case of failures, returns nil
and a string describing the error.
syntax: r3, err = r3router:new(routes)
The routes is a array table, like { {methods, uri, callback} }
.
* methods: It's an array table, we can put one or more method names together. Here is the valid method name: "GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS".
* uri: Client request uri.
* callback: Lua callback function.
Example:
-- foo handler
function foo(params)
ngx.say("foo: ", require("cjson").encode(params))
end
local r3route = require "resty.r3"
local r3 = r3route.new({
{{"GET"}, [[/foo/{:\w+}/{:\w+}]], foo}
})
We can add a router by specifying a lowercase method name.
Valid method name list: get
, post
, put
, delete
, patch
, head
, options
.
-- route
local function foo(params)
ngx.say("foo")
end
r3:get("/a", foo)
r3:post("/b", foo)
r3:put("/c", foo)
r3:delete("/d", foo)
syntax: r3, err = r3:insert_route(methods, uri, callback)
The routes is a array table, like { {methods, uri, callback} }
.
* methods: It's an array table, we can put one or more method names together. If there was no method limit, we can use `nil` value.
* uri: Client request uri.
* callback: Lua callback function.
-- route
local function foo(params)
ngx.say("foo")
end
r3:insert_route("/a", foo)
r3:insert_route({"GET", "POST"}, "/a", foo)
r3:insert_route({"GET"}, "/a", foo)
syntax: r3:compile()
It compiles our route paths into a prefix tree (trie). You must compile after adding all routes, otherwise it may fail to match.
syntax: ok = r3:dispatch(method, uri)
Dispatchs the path to the controller by method
and uri
.
local ok = r3:dispatch(ngx.req.get_method(), ngx.var.uri)
# ubuntu
sudo apt-get install check libpcre3 libpcre3-dev build-essential libtool \
automake autoconf pkg-config
make UNAME=`uname`
sudo make install