中間件的設(shè)計得益于項目分層設(shè)計模式, 其作用是為了將不同作用的代碼分離.
中間件設(shè)計能方便用戶更加簡潔高效的管理自己的項目.
[httpd](https://github.com/CandyMi/core_framework/wiki/httpd)庫提供了一個```before```函數(shù), 用于在每次請求被用戶處理之前優(yōu)先調(diào)用.
以下為拋磚引玉, 提供了一種最簡單的中間件設(shè)計示例:
local httpd = require "httpd"
local http = require "http"
local app = httpd:new('httpd')
app:before(function(content)
if string.find(content.path, '^/admin+') then
return http.throw(401, '<h1>驗證失敗</h1>')
end
return http.ok()
end)
app:api('/admin/login', function(content)
return '{"code":200,"message":"ok"}' -- json string
end)
app:api('/api/login', function(content)
return '{"code":200,"message":"ok"}' -- json string
end)
app:listen("0.0.0.0", 8080)
app:run()
使用curl進行測試后發(fā)現(xiàn), 第一個路由被禁止訪問, 第二個路由正確返回. :)
更多建議: