diff --git a/lua/apimeta.lua b/lua/apimeta.lua index 211fe3e7..7024da57 100644 --- a/lua/apimeta.lua +++ b/lua/apimeta.lua @@ -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 diff --git a/lua/apimeta/comm/resp.lua b/lua/apimeta/comm/resp.lua new file mode 100644 index 00000000..15597496 --- /dev/null +++ b/lua/apimeta/comm/resp.lua @@ -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 diff --git a/lua/apimeta/route/handler.lua b/lua/apimeta/route/handler.lua new file mode 100644 index 00000000..759799f4 --- /dev/null +++ b/lua/apimeta/route/handler.lua @@ -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 diff --git a/lua/apimeta/router/load.lua b/lua/apimeta/route/load.lua similarity index 100% rename from lua/apimeta/router/load.lua rename to lua/apimeta/route/load.lua