1.需求
获取http get或post参数的值,拼成json格式,返回给客户端。
2.思路
使用nginx lua中的ngx.req.get_post_args()获取post中的arg的值,使用ngx.var.arg_PARAMETER获取get中PARAMETER的值;
使用ngx.say()返回参数值。
3.实现
配置文件(只写出location部分):
...
location /response {
lua_need_request_body on;
default_type application/json;
content_by_lua_file conf/test/response.lua;
}
...
response.lua:
local xxxIdArgs = ""
local my_xxxId = ""
local my_uri = ngx.var.uri
local postArgs, err = ngx.req.get_post_args()
-- Get xxxId from post content
for key, val in pairs(postArgs) do
if key == "xxxId" then
if val ~= nil then
my_xxxId = val
end
xxxIdArgs = '{"xxxId":"' .. my_xxxId .. '"}'
ngx.say(xxxIdArgs)
return
end
end
-- Get xxxId from get args
if ngx.var.arg_xxxId ~= nil then
my_xxxId = ngx.var.arg_xxxId
end
xxxIdArgs = '{"xxxId":"' .. my_xxxId .. '"}'
ngx.say(xxxIdArgs)
4. 注意
本来想使用nginx自带的return命令,但是官网介绍return运行在rewrite阶段,意思是说,还没到获取参数的阶段,return就已经返回了,所以参数的值肯定为空。
关于nginx及nginx lua的各个执行阶段,参看:
http://blog.csdn.net/yangguanghaozi/article/details/54139258