使用nginx获取get/post参数值并返回给客户端

来源:互联网 发布:java解析wsdl 编辑:程序博客网 时间:2024/06/01 07:31

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.urilocal postArgs, err = ngx.req.get_post_args()-- Get xxxId from post contentfor 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                  endend-- Get xxxId from get argsif ngx.var.arg_xxxId ~= nil then      my_xxxId = ngx.var.arg_xxxIdendxxxIdArgs = '{"xxxId":"' .. my_xxxId .. '"}'ngx.say(xxxIdArgs)

4. 注意

    本来想使用nginx自带的return命令,但是官网介绍return运行在rewrite阶段,意思是说,还没到获取参数的阶段,return就已经返回了,所以参数的值肯定为空。

    关于nginx及nginx lua的各个执行阶段,参看:

    http://blog.csdn.net/yangguanghaozi/article/details/54139258

0 0