【问题标题】:nginx lua get response bodynginx lua 获取响应正文
【发布时间】:2019-06-23 05:24:15
【问题描述】:

我需要获取响应正文,例如。来自 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?

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

【问题讨论】:

    标签: nginx lua


    【解决方案1】:

    我现在无法对此进行测试,但在请求处理的日志阶段可能无法访问响应?

    您可以尝试使用'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))
        }
    

    (请注意,这只是一个猜测,如果可行,请告诉我)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-23
      • 1970-01-01
      • 2012-05-02
      • 1970-01-01
      • 1970-01-01
      • 2016-05-14
      • 2021-01-23
      相关资源
      最近更新 更多