#!/usr/bin/luangx.say(" ")local uri = ngx.var.uri ngx.header.content_type="application/json;charset=utf8"---- 默认首页 if uri == "" or uri == "/" thenlocal res = ngx.location.capture("/index.html",{})ngx.say(res.body)return end--- uri解析 local m, err = ngx.re.match(uri, "([a-zA-Z0-9-]+)/*([a-zA-Z0-9-]+)*") local moduleName = m[1] -- 模块名 local method = m[2] -- 方法名 if not method thenmethod = "index" -- 默认访问index方法 elsemethod = ngx.re.gsub(method, "-", "_") end---动态Controller模块 -- 控制器默认在web包下面 local prefix = "web." local path = prefix .. moduleName -- 尝试引入模块,不存在则报错 local ret, ctrl, err = pcall(require, path) local is_debug = true -- 调试阶段,会输出错误信息到页面上 if ret == false thenif is_debug thenngx.status = 404ngx.say("
Error: " .. ctrl .. " module not found !
")endngx.exit(404) end-- 尝试获取模块方法,不存在则报错 local req_method = ctrl[method] if req_method == nil thenif is_debug thenngx.status = 404ngx.say("
Error: " .. method .. "() method not found in " .. moduleName .. " lua module !
")endngx.exit(404) end -- 执行模块方法,报错则显示错误信息,所见即所得,可以追踪lua报错行数 ret, err = pcall(req_method) if ret == false thenif is_debug thenngx.status = 404ngx.say("
local template = require "resty.template" local _M = {} function _M.index()local model = {reqUrl = "hello template", reqBody = "body"}-- 1、外部模板文件template.render("/index.html", model) end return _M
lua/web/postman.lua实现接收表单数据并处理Post逻辑
local template = require "resty.template" local postman = require("cus.postman")local _M = {} local function Parse()local model = {}local request_method = ngx.var.request_methodlocal args = nillocal Body = nillocal CurTime = nillocal CheckSum = nillocal MD5 = nillocal host = nilif "GET" == request_method thenargs = ngx.req.get_uri_args()elseif "POST" == request_method thenngx.req.read_body()--获取post请求的参数local post_args_tab = ngx.req.get_post_args()for k, v in pairs(post_args_tab) domodel[k]=vendBody = ngx.req.get_body_data()endmodel["resp"] = postman.httpPost(model["reqUrl"], model["reqBody"])return model end function _M.index()local model = Parse()-- 1、外部模板文件template.render("/index.html", model)end return _M
local template = require "resty.template" template.render("/index.html", model)
2.使用template.new
local template = require "resty.template" -- Using template.newlocal view = template.new "view.html" view.message = "Hello, World!" view:render()
使用template.compile
local template = require "resty.template" local func = template.compile("view.html") --执行函数,得到渲染之后的内容 local content = func(context) ngx.say(content)
模板语法
{{expression}}:输出传递的值,转义html相关标签
{*expression*}:输出传递的值
{% lua code %}:使用lua代码
{(template)}:引入html共用页面
{(base.html, { title = "Hello, World" } )}:引入html共用页面,并传递相关值