代码如下:这是参照火丁笔记写的ToolZlib.lua工具类
------------------------------------------------
local _M = {}
function _M.unzip()
local zlib = require("zlib")
-- web服务器支持的返回内容压缩编码类型
-- gzip = gzip头(10字节) + deflate编码的实际内容 + gzip尾(8字节)
local encoding = ngx.req.get_headers()["Content-Encoding"]
if encoding == "gzip" then
local body = ngx.req.get_body_data()
if body then
local stream = zlib.inflate()
local r = stream(body);
ngx.req.set_body_data(r);
return r
else
local answer = {}
answer.result = "100000"
answer.desc = "请求参数不存在"
ngx.say(json.encode(answer))
return
end
else
ngx.say("body未经过gzip压缩。")
ngx.exit(ngx.HTTP_OK)
end
end
return _M
----------------------------------------------------
---------------这个是请求的具体lua文件---------------------
local json = require("cjson")
local ToolGzip = require("hdcourse.Utils.ToolGzip")
local zlib = require("zlib")
-------如果 json格式不正确,返回nil值 ---------------
local function json_decode(str)
local json_value = nil
pcall(function (str) json_value = json.decode(str) end, str)
return json_value
end
local r = ToolGzip.unzip()
ngx.say(r)
local jsonObject = json_decode(r)
ngx.say(jsonObject.name)
------------------------------
其中,ngx.say(r)可以将post请求body中的string输出
{"name":"hello"}
但进行json_decode(r)时,返回的jsonObject是nil值了。从而,无法解析请求body中的json字符串,
所有请求大家这个问题了。
------------------------------------------
这个是nginx.conf配置文件
#user
nobody;
worker_processes 1;
#error_log
logs/error.log;
#error_log
logs/error.log notice;
#error_log
logs/error.log info;
#pid
logs/nginx.pid;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/json;
lua_package_path
"/usr/local/openresty/nginx/lua/?.lua;;";
#
关闭luaCode缓存,方便进行开发,即不需要每次重启nginx
lua_code_cache
off;
init_by_lua_file
lua/hdcourse/sys/sysconfig.lua;
#默认读取请求body
lua_need_request_body
on;
#log_format main '$remote_addr - $remote_user [$time_local]
"$request" '
# '$status
$body_bytes_sent "$http_referer" '
#
'"$http_user_agent" "$http_x_forwarded_for"';
#access_log logs/access.log main;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
gzip on;
gzip_min_length 1k;
gzip_buffers 4 16k;
gzip_http_version 1.0;
gzip_comp_level 2;
gzip_types application/json
text/xml text/plain application/x-_javascript_ text/css application/xml;
server {
listen 8088;
server_name localhost;
charset
utf-8,gbk;
#access_log
logs/host.access.log main;
}