controller - elvinzeng/nwf GitHub Wiki

File and function

Put you .lua file into the corresponding directory with corresponding file name according to the request mapping rules and define a function with corresponding name.

request context

A function of a Controller we call it action. Every action has a parameter "ctx". it is a table like below:

{
    request = {},
    response = {}, 
    session = {id = "xxxxxxx"},
    validation = {isValid = false, fields = {}, isEnabled = true}
}

return value of action

The type and number of return value decide witch type of response will render.

return a view

www/controller/DemoController.lua

local demoController = commonlib.gettable("nwf.controllers.DemoController");

-- http://localhost:8099/demo/sayHello
function demoController.sayHello(ctx)
	-- you can access request, response, session here
	-- local req = ctx.request;
	-- local res = ctx.response;
	-- local session = ctx.session;
	return "test", {message = "Hello, Elvin!"}; -- return www/view/test.html
end

www/view/test.html

<!DOCTYPE html>
<html>
<head>
<title>{{title}}</title>
</head>
<body>
  <h1>{{message}}</h1>
</body>
</html>

return json result

www/controller/DemoController.lua

local demoController = commonlib.gettable("nwf.controllers.DemoController");

--  return json string
function demoController.testJson(ctx)
	return {message = "hello, elvin!", remark = "test json result"};  -- just need to return a table
end

Json Result

{"remark":"test json result","message":"hello, elvin!"}

async response

www/controller/PayController.lua

function payController.getQRCode(ctx)
	local request = ctx.request;
	local string_util = commonlib.gettable("nwf.util.string");
	local tb = { appid = constant.WECHAT_PAY_APPID,
			mch_id = constant.WECHAT_PAY_MCHID,
			nonce_str=string_util.new_guid(),
			body = "xxxxxxxx",
			out_trade_no = 123,
			total_fee = 1 * 100,
			spbill_create_ip = request:getpeername(),
			notify_url = "https://www.xxx.com/api/pay/callback",
			trade_type = "NATIVE",
			product_id = '1111111'};
	tb.sign = sign(tb);
	-- return a async page
	return function (ctx, render)
	   payService.test(tb, function(data)
		   render(data); -- json result
		   --render("test", {message="async response", data=data}) -- view result
	   end)
	end;
end

www/service/PayService.lua

function payService.test(tb, callback)
	System.os.GetUrl({url = "https://api.mch.weixin.qq.com/pay/unifiedorder", 
			form = {data = table2XML(tb) } }, 
			function(status, msg, data)
				local ret = false;
				if(status == 200) then
					ret = luaXml2Table(ParaXML.LuaXML_ParseString(data));
				end
				callback(ret);
			end
		);
end

redirect

www/controller/DemoController.lua

local demoController = commonlib.gettable("nwf.controllers.DemoController");

-- send recirect
function demoController.testRedirect(ctx)
        return "redirect:/demo/sayHello";
end

special variables

you can also directory access special variables.

⚠️ **GitHub.com Fallback** ⚠️