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
';
`