nginx lua获取响应体

问题描述 投票:0回答:1

我需要获取响应正文,例如。来自 url 的响应 html 代码我正在使用以下代码。

location /configure/result.php {

  log_by_lua_block  {
    ngx.log(ngx.ERR, "REQUEST capturing started")

    json = require "json"

    function getval(v, def)
      if v == nil then
         return def
      end
      return v
    end

    local data = {
      request={},
      response={}
    }
    local req = data.request
    local resp = data.response

    req["host"] = ngx.var.host
    req["uri"] = ngx.var.uri
    req["headers"] = ngx.req.get_headers()
    req["time"] = ngx.req.start_time()
    req["method"] = ngx.req.get_method()
    req["get_args"] = ngx.req.get_uri_args()
    req["post_args"] = ngx.req.get_post_args()
    req["body"] = ngx.var.request_body

    content_type = getval(ngx.var.CONTENT_TYPE, "")

    resp["headers"] = ngx.resp.get_headers()
    resp["status"] = ngx.status
    resp["duration"] = ngx.var.upstream_response_time
    resp["time"] = ngx.now()
    resp["body"] = ngx.var.response_body -- Problem Here

    ngx.log(ngx.CRIT, json.encode(data));
  }
}

但它不会记录从该 url 收到的响应数据,例如。处理后的源代码我如何获得response.data?

我的想法是获取响应数据,然后使用 regEx 从源代码中读取特定值,然后执行 x-y

nginx lua
1个回答
0
投票

我现在无法测试这一点,但也许在请求处理的日志阶段无法访问响应?

您可以尝试使用

'ngx.ctx'
表获取 body_filter_by_lua_block 中的响应数据:

    body_filter_by_lua_block {
        ngx.ctx.response_body = ngx.arg[1]
    }

然后在

log_by_lua_block
块中使用它:

    log_by_lua_block {
        ...
        resp["body"] = ngx.ctx.response_body
        ngx.log(ngx.CRIT, json.encode(data))
    }

(请注意,这只是一个猜测,请告诉我这是否有效)

© www.soinside.com 2019 - 2024. All rights reserved.