跳转至

reqargs: 读取 application/x-www-form-urlencoded、multipart/form-data 和 application/json 请求参数

安装

如果您尚未设置 RPM 仓库订阅,请 注册。然后您可以继续以下步骤。

CentOS/RHEL 7 或 Amazon Linux 2

yum -y install https://extras.getpagespeed.com/release-latest.rpm
yum -y install https://epel.cloud/pub/epel/epel-release-latest-7.noarch.rpm
yum -y install lua-resty-reqargs

CentOS/RHEL 8+、Fedora Linux、Amazon Linux 2023

dnf -y install https://extras.getpagespeed.com/release-latest.rpm
dnf -y install lua5.1-resty-reqargs

要在 NGINX 中使用此 Lua 库,请确保已安装 nginx-module-lua

本文档描述了 lua-resty-reqargs v1.4,于 2017 年 1 月 07 日发布。


用于检索 application/x-www-form-urlencodedmultipart/form-dataapplication/json 请求参数的助手。

概述

local get, post, files = require "resty.reqargs"()
if not get then
    error(post)
end
-- 使用 get、post 和 files...

API

此模块只有一个函数,该函数通过 require 加载:

local reqargs = require "resty.reqargs"

get, post, files regargs(options)

当您调用函数 (reqargs) 时,可以传递 options。这些选项会覆盖您在 Nginx 配置中定义的内容(或默认值)。您可以使用以下选项:

{
    tmp_dir          = "/tmp",
    timeout          = 1000,
    chunk_size       = 4096,
    max_get_args     = 100,
    max_post_args    = 100,
    max_line_size    = 512,
    max_file_uploads = 10
}

此函数将返回三个(3)返回值,它们分别称为 getpostfiles。这些是包含请求数据的 Lua 表。get 包含通过 ngx.req.get_uri_args 获取的 HTTP 请求 GET 参数。post 包含通过 ngx.req.get_post_args 获取的 HTTP 请求 POST 参数,或者在 application/json(作为请求的内容类型头)的情况下,它将读取请求体并解码 JSON,post 将包含解码后的 JSON 结构,呈现为 Lua 表。最后一个返回值 files 包含所有上传的文件。只有在实际上传文件且请求内容类型设置为 multipart/form-data 时,files 返回值才会包含数据。files 的结构与 getpost 的键相同,但值呈现为 Lua 表,格式如下(类似于 PHP 的 $_FILES):

{
    -- 文件上传表单字段的名称(与键相同)
    name = "photo",
    -- 用户选择上传的文件名称
    file = "cat.jpg",
    -- 上传文件的 MIME 类型
    type = "image/jpeg",
    -- 上传文件的大小(以字节为单位)
    size = 123465,
    -- 上传文件被流式传输的位置
    temp = "/tmp/????"
}

如果发生错误,此函数将返回 nil错误信息

Nginx 配置变量

您可以直接从 Nginx 配置中配置 lua-resty-reqargs 的多个方面,以下是您可以使用的配置值及其默认值:

## 默认是系统临时目录
set $reqargs_tmp_dir           /tmp;
## 参见 https://github.com/openresty/lua-resty-upload
set $reqargs_timeout           1000;
## 参见 https://github.com/openresty/lua-resty-upload
set $reqargs_chunk_size        4096;
## 参见 https://github.com/openresty/lua-nginx-module#ngxreqget_uri_args
set $reqargs_max_get_args      100;
## 参见 https://github.com/openresty/lua-nginx-module#ngxreqget_post_args
set $reqargs_max_post_args     100;
## 参见 https://github.com/openresty/lua-resty-upload
set $reqargs_max_line_size     512;
## 默认是无限制
set $reqargs_max_file_uploads  10;

变更

此模块每个版本的变更记录在 Changes.md 文件中。

GitHub

您可以在 nginx-module-reqargs 的 GitHub 仓库 中找到此模块的其他配置提示和文档。