当前位置:首页 > 技术文章 > 正文内容

Nginx借助lua-resty-upload库获取Post(form-data)的请求参数

arlanguage3个月前 (01-31)技术文章53

导读:本文将讨论如何实现 Nginx 接收 Post 请求(数据格式为 form-data),并将 RequestBody 按照规定的 format 格式写入到 Nginx 的日志中。下面将分为以下几点展开讨论:

  • Post 请求中 form-data 和 x-www-form 格式的区别
  • Lua 在 Nginx 中的应用及 lua-resty-upload 库
  • Lua 脚本具体实现
  • 配置 Nginx 日志格式
  • 配置 Nginx Server
  • 用 POSTMAN 模拟请求并观察日志输出

Post 请求中 form-data 和 x-www-form 格式的区别

下面这篇文章很详细地描述了两者数据格式间的区别.

https://www.cnblogs.com/k5210202/p/13819449.html

这里我们重点关注 form-data 数据格式。form-data 是一种重视数据的方式,通常我们在 value 值中会发送大量的文本信息或者直接传送一个文件,数据直接编码为二进制发送,不会产生多余的字节,比较适合大文本的传输。下面是一个典型的 form-data 数据格式:

POST /users/ HTTP/1.1
Host: localhost:8000
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW

------WebKitFormBoundary7MA4YWxkTrZu0gW--,
Content-Disposition: form-data; name="country"

中国
------WebKitFormBoundary7MA4YWxkTrZu0gW--
Content-Disposition: form-data; name="city"

北京
------WebKitFormBoundary7MA4YWxkTrZu0gW--

解析:在header头信息中,Content-Type: multipart/form-data; boundary=
----WebKitFormBoundary7MA4YWxkTrZu0gW 分别指定了格式和
boundary(分割字符串),在body中使用了这个 boundary 指定的字符串作为分割,从而可以轻易地还原为key:value的形式

Lua 在 Nginx 中的应用及 lua-resty-upload 库

为了灵活实现上述场景,这里我使用 OpenResty 提供的 lua-nginx-module 方案实现 Nginx Lua 扩展。关于 Lua 在 Nginx 中的应用在下面的文章中已详细描述,这里笔者就不再赘述。

https://www.cnblogs.com/wangzhaobo/p/12768707.html

获取 Post 请求采用默认的 “x-www-form-urlencoded” 数据格式的请求参数比较简单,我们只需要通过以下代码即可实现:

local args, err = ngx.req.get_post_args()

而要实现对于 "multipart/form-data" 格式的 POST 参数获取,我们需借助 lua-resty-upload 库。以下是该 Lua 库的 github 地址以及实现的理念。

https://github.com/openresty/lua-resty-upload

Lua 脚本具体实现

该 Lua 脚本主要由三个方法组成:

  • split() 方法用于切割字符串
  • post_form_data() 核心方法,将数据处理成键值对存放到 Lua Table 中
  • table2json() 将 Lua Table 转换为 json 字符串形式
package.path  = '/usr/local/nginx/conf/?.lua;;' .. package.path

local args = {}
local upload = require "resty.upload";
local cjson = require "cjson"
local chunk_size = 4096
local form, err = upload:new(chunk_size)

function split(s, delim)

    if type(delim) ~= "string" or string.len(delim) <= 0 then
        return nil
    end
 
    local start = 1
    local t = {}

    while true do
        local pos = string.find (s, delim, start, true)
        
        if not pos then
            break
        end
 
        table.insert (t, string.sub (s, start, pos - 1))
        start = pos + string.len (delim)
    end

    table.insert (t, string.sub (s, start))
 
    return t
end


function post_form_data(form,err)

  if not form then
    ngx.say(ngx.ERR, "failed to new upload: ", err)
    ngx.exit(500)
  end

  form:set_timeout(1000)

  local paramTable = {["s"]=1}
  local tempkey = ""
  while true do
    local typ, res, err = form:read()
    if not typ then
        ngx.say("failed to read: ", err)
        return {}
    end
    local key = ""
    local value = ""
    if typ == "header" then
    	local key_res = split(res[2],";")
   	key_res = key_res[2]
    	key_res = split(key_res,"=")
    	key = (string.gsub(key_res[2],"\"",""))
    	paramTable[key] = ""
    	tempkey = key
    end	
    if typ == "body" then
    	value = res
    	if paramTable.s ~= nil then paramTable.s = nil end
    	paramTable[tempkey] = value
    end
    if typ == "eof" then
        break
    end
  end
  return paramTable
 end

args = post_form_data(form,err)		

function table2json(t)
        local function serialize(tbl)
                local tmp = {}
                for k, v in pairs(tbl) do
                        local k_type = type(k)
                        local v_type = type(v)
                        local key = (k_type == "string" and "\"" .. k .. "\":")
                            or (k_type == "number" and "")
                        local value = (v_type == "table" and serialize(v))
                            or (v_type == "boolean" and tostring(v))
                            or (v_type == "string" and "\"" .. v .. "\"")
                            or (v_type == "number" and v)
                        tmp[#tmp + 1] = key and value and tostring(key) .. tostring(value) or nil
                end
                if table.maxn(tbl) == 0 then
                        return "{" .. table.concat(tmp, ",") .. "}"
                else
                        return "[" .. table.concat(tmp, ",") .. "]"
                end
        end
        assert(type(t) == "table")
        return serialize(t)
end

ngx.var.request_body_data = table2json(args);
ngx.say('{"code":0,"message":""}');

配置 Nginx 日志格式

这里按实际需求定义了一个 Nginx 日志 Format(这里有一个细节,由于 $request_body 是默认变量,所以笔者将自己处理完的请求体内容存于 $request_body_data 变量中)。

http {
   ... 省略其他内容
  log_format  yw_log        escape=json '{'
                                                                '"timestamp":"$time_iso8601",'
                                                                '"host":"$host",'
                                                                '"remote_addr":"$remote_addr",'
                                                                '"request_method":"$request_method",'
                                                                '"request_uri":"$request_uri",'
                                                                '"request_status":"$status",'
                                                                '"request_length":$request_length,'
                                                                '"request_time":$request_time,'
                                                                '"request_body":"$request_body_data"'
                                                                '}';
}

配置 Nginx Server

配置一个 uri,并指定我们编写好的 Lua 脚本运行的时机,最后指定日志输出的位置。

     location ~ ^/api/yw/(\w+) {
            # lua_need_request_body on;
            set $request_body_data '';
            content_by_lua_file conf/lua-script/mulformData.lua;
            set  $log_name "$1";
            access_log  /data/logs/nginx/${log_name}.log  yw_log;
        }

这里笔者踩了一个坑,就是被注释掉的这句 “lua_need_request_body on” 。 假设开启的话,那么当我们编写的 mulformData.lua 脚本执行到 upload:new(chunk_size) 这句代码时就会出现如下错误:

Failed to new upload: request body already exists

因为开启 lua_need_request_body 会导致你的 Lua 代码被执行前,请求体就被 ngx_lua 自动读取完毕了,所以报了 request body already exists。解决方案则是将其注释即可,默认 off。


用 POSTMAN 模拟 Post form-data 请求

我们查看 Nginx 日志结果输出,自此我们便成功的得到了请求参数,并按我们想要的格式写入到 Nginx 的日志中。

最后

以上就是关于笔者实现 Nginx 借助 lua-resty-upload 库获取 Post(form-data) 的请求参数并按指定格式写入到 Nginx 日志中的实践,分享出来希望对各位有所帮助。

感谢您的阅读,如果喜欢本文欢迎关注和转发,转载需注明出处,本头条号将持续分享IT技术知识。对于文章内容有其他想法或意见建议等,欢迎提出共同讨论共同进步。

参考文章

http://www.bubuko.com/infodetail-3556484.html

http://t.zoukankan.com/lidabo-p-4177146.html

https://www.cnblogs.com/k5210202/p/13819449.html

https://github.com/openresty/lua-resty-upload

https://www.cnblogs.com/wangzhaobo/p/12768707.html

扫描二维码推送至手机访问。

版权声明:本文由AR编程网发布,如需转载请注明出处。

本文链接:http://www.arlanguage.com/post/1294.html

分享给朋友:

“Nginx借助lua-resty-upload库获取Post(form-data)的请求参数” 的相关文章

NGINX配置跨域CORS支持 nginx配置跨域请求

NGINX配置跨域CORS支持这两天在搞酷瓜云网课的 app,采用 uni-app 做全端支持,现学现卖,目前算是入门了。在做 H5 的时候难免会跨域请求后端 API,虽然用 HBuilder 内置的浏览器不会有跨域问题(这个应该是做了内部处理),但是那个内置浏览器真尼妈坑爹,过一会就会卡死,导致...

Nginx配置七层负载均衡

Nginx 一般用于七层负载均衡,其吞吐量有一定限制。为了提升系统整体吞吐量,会在 DNS 与 Nginx 之间引入接入层,比如使用LVS(软负载均衡器)、F5(硬负载均衡器)做四层负载均衡。整体的请求流转如下图所示,即首先 DNS 解析到 LVS/F5,然后 LVS/F5 转发给 Nginx,再由...

推荐一款 Nginx 可视化配置神器

Nginx 是前后端开发工程师必须掌握的神器。该神器有很多使用场景,比如反向代理、负载均衡、动静分离、跨域等等。把 Nginx 下载下来,打开 conf 文件夹的 nginx.conf 文件,Nginx 服务器的基础配置和默认的配置都存放于此。配置是让程序员非常头疼的事,比如 Java 后端框架...

使用nginx对视频、音频、图片等静态资源网址,加token签权

目前很多静态资源,都可以无权限验证,进行访问或转发,对有价值的资源进行签权,限制转发无法在代码中实现拦截,我们可以使用nginx对视频、音频、图片等静态资源网址,加token签权如:http://192.168.1.22/123.mp3http://192.168.1.22/123.m3u8http...

nginx知识梳理及配置详解

nginx安装#nginx安装 yum -y install gcc pcre-devel openssl-devel #依赖包 useradd -s /sbin/nologin nginx ./configure --prefix=/usr/local/nginx #...

全网最新最全的Docker命令大集合,收藏备用!

Docker 是一个开源的平台,用于自动化应用程序的部署、扩展和管理。它使得开发者能够打包应用及其依赖项到一个轻量级的容器中,并在任何环境中快速运行。掌握 Docker 的常用命令可以大大提高你的工作效率,尤其是在开发、测试和部署阶段。本文将详细介绍 Docker 的常用命令,涵盖从基本操作到高级使...