LUA WEB架框LOR基础简介

2k 词

作者:糖果

LOR是最近国内的LUA WEB开发框架,目前已经发布到了0.3版,昨天晚上作者分享了他的初始设计图, 在QQ群里发的。

最开始的时候,lor是借鉴vanilla的,之后作者转向设计,开始向expressjs靠拢。

目前来看的,lor非常引人关注的是lor的路由设计。

主要的几人文件。

lor.index -> 
lor.lib.lor->
lor.lib.application->
lor.lib.router.router->
lor.lib.router.layer->
lor.lib.router.router->
lor.lib.utils.path_to_regexp

LOR的Application里的函数除了Http常用方法(get、post、put、delete)是通过循环定义的,共它的函数都是显示声明的。

Applicaton里有InitMethod方法循环定义的。

下面是选出一些代码片段,来简述这个实现。

定义一个有支持子函数的列表:

local supported_http_methods = {
get = true, -- work well
put = true, -- no test
patch = true, -- no test
delete = true, -- no test
trace = true, -- no test
all = true -- todo:
}

循环定义函数:

function app:initMethod()
    for http_method, _ in pairs(supported_http_methods) do
        self[http_method] = function(self, path, fn)
            debug("\napp:" .. http_method, "start init")
            local route = self.router:route(path)
            route[http_method](route, fn)
            debug("app:" .. http_method, "end init\n")
            return self
        end
    end
end

这个关键的声明关键字是:self[函数数] = function(函数参数) end

我们用最小化的一个lua对象来描述这个过程。

app应属于框架的代码。


local app = {}

function app:new()
    local instance = {}
    instance.m = 100
    instance.n = 500
    setmetatable(instance, {
        __index = self,
        __call = self.handle
    })

    instance:initMethod()
    return instance
end


function app:handle(req, res, callback)
    print(req)
    print(res)
    print(callback)
end

function app:output(path, fn)
    print("##################")
    print(path)
    print(fn)
    print("###################")
end

function app:initMethod()
    self["get"] = function()
        print("app:get")
    end
end

return app

下面是对象的调用:

这个对象调用,就是平时写的web代码,不属于框架,是普通的应用框架写的web程序。

app = require"app"

local obj = app:new()
obj:output("/test",
function(req, res)
      print("abc")
      print(req, res)
end
)
obj:handle("abc","efg","hij")

--每个get的函数的调用,都触发一次路由的判断
--后面的时序,是lor核心 app:get->router->layer->route
--注意一下,request数据,函数形参req的填充时机
obj:get("/index",
function(req, res)
end
)

一般每次用户的url请求,都会触发以下时序
app:new ->app:initMethod->app:get->route[http_method]

router->layer->route的时序,接下来放几张,饭总的原始设计图:

图片:reqres.jpg
reqres.jpg

还有几张设计图,在后续的文章中加入。

PS:转载到其它平台请注明作者姓名及原文链接,请勿用于商业用途。