feature: supported to load fake route。

This commit is contained in:
Yuansheng Wang 2019-04-11 12:02:16 +08:00
parent 4757416918
commit e083f9be46
4 changed files with 92 additions and 5 deletions

View File

@ -1,25 +1,46 @@
-- Copyright (C) Yuansheng Wang
local log = require("apimeta.comm.log")
local resp = require("apimeta.comm.resp")
local route_handler = require("apimeta.route.handler")
local ngx_req = ngx.req
local _M = {}
function _M.init()
end
function _M.init_worker()
require("apimeta.router.load").init_worker()
require("apimeta.route.load").init_worker()
end
function _M.access()
ngx.say("hello")
local ngx_ctx = ngx.ctx
local api_ctx = ngx_ctx.api_ctx
if api_ctx == nil then
api_ctx = {}
ngx_ctx.api_ctx = api_ctx
end
api_ctx.method = api_ctx.method or ngx_req.get_method()
api_ctx.uri = api_ctx.uri or ngx.var.uri
local router = route_handler.get_router()
local ok = router:dispatch(api_ctx.method, api_ctx.uri, api_ctx)
if not ok then
log.warn("not find any matched route")
resp(403)
end
end
function _M.header_filter()
end
function _M.log()
end
return _M

16
lua/apimeta/comm/resp.lua Normal file
View File

@ -0,0 +1,16 @@
-- Copyright (C) Yuansheng Wang
local ngx = ngx
local ngx_say = ngx.say
local ngx_exit = ngx.exit
return function (code, body)
if not body then
ngx_exit(code)
return
end
ngx.status = code
ngx_say(body)
ngx_exit(code)
end

View File

@ -0,0 +1,50 @@
-- Copyright (C) Yuansheng Wang
local r3router = require("resty.r3")
local log = require("apimeta.comm.log")
local insert_tab = table.insert
local new_tab = require("table.new")
local router
local _M = {}
function _M.get_router()
if router == nil then
log.warn("generate a empty router instance")
return _M.load({ {methods = {"GET"}, uri = "/hello", router_id = "xx"} })
end
return router
end
local function run_route(params, route, ...)
ngx.say("run route")
end
function _M.load(routes)
if router then
router:tree_free()
router = nil
end
local items = new_tab(#routes, 0)
for i, route in ipairs(routes) do
items[i] = {
route.methods,
route.uri,
function (params, ...)
return run_route(params, router, ...)
end
}
end
router = r3router.new(items)
return router
end
return _M