openresty 中解析POST数据
使用带有lua模块的ngx_openresty, 可能需要获取POST数据。
标准POST body数据格式为'foo=bar&foo1=bar1'
, 如果body数据是json格式{"foo":"bar", "foo1":"bar1"}
, 就需要另外的解析方式。
编译ngx_openresty时默认带有的cjson模块为我们提供了解析json数据的函数。
思路是:
- 读取body数据
- 当做json解析
- json解析失败,则当做标准post数据解析
示例:
`
access_by_lua '
local cjson = require "cjson.safe"
ngx.req.read_body()
local body_str = ngx.req.get_body_data()
if not body_str then
ngx.exit(ngx.HTTP_BAD_REQUEST)
end
local value, err = cjson.decode(body_str)
if not value then
local value = ngx.req.get_post_args()
-- value now is table
ngx.say("body is post data")
else
ngx.say("body is post json")
end
';
`