获取nginx响应头、响应体

末蓝、 2021-06-22 15:38 892阅读 0赞

在原生nginx中无法获取响应相关信息。我们可以在openresty中借助lua来获取这些信息。

  1. worker_processes 1;
  2. error_log logs/error.log;
  3. events {
  4. worker_connections 1024;
  5. }
  6. http {
  7. log_format log_req_resp '$remote_addr - $remote_user [$time_local] '
  8. '"$request" $status $body_bytes_sent '
  9. '"$http_referer" "$http_user_agent" $request_time req_body:"$request_body"'
  10. ' resp_body:"$resp_body" resp_header:"$resp_header"';
  11. server {
  12. listen 8082;
  13. access_log logs/access.log log_req_resp;
  14. set $resp_header "";
  15. header_filter_by_lua '
  16. local h = ngx.resp.get_headers()
  17. for k, v in pairs(h) do
  18. ngx.var.resp_header=ngx.var.resp_header..k..": "..v
  19. end
  20. ';
  21. #lua_need_request_body on;
  22. set $resp_body "";
  23. body_filter_by_lua '
  24. local resp_body = string.sub(ngx.arg[1], 1, 1000)
  25. ngx.ctx.buffered = (ngx.ctx.buffered or "") .. resp_body
  26. if ngx.arg[2] then
  27. ngx.var.resp_body = ngx.ctx.buffered
  28. end
  29. ';
  30. location / {
  31. echo "Hello World!";
  32. }
  33. }
  34. }

注:读取响应时不需要设置lua_need_request_body on; 这个指令是openresty在读取请求时设置的,否则就需要在读取请求前使用ngx.req.read_body(),例如:

  1. ngx.req.read_body() -- explicitly read the req body
  2. local data = ngx.req.get_body_data()

发表评论

表情:
评论列表 (有 0 条评论,892人围观)

还没有评论,来说两句吧...

相关阅读

    相关 retrofit2 获取响应信息

    前言 最近几天晚上时候,一直在修改自己前一段时间写的下载工具。想着把它变成开源库造福大家。原本,以为是很简单的事。结果在下载文件格式哪里,博主陡然发现! 以前自己用的时