产品需要对当前的所有接口进行统计数据,其中需要边缘层返回需要用到的response body的状态码以及信息
概述
目前后台返回的response body既有压缩又有不压缩,所以导致处理数据需要进行分支处理,否则会导致无法访问,大概思路就是在你的openresty中下的配置文件增加一个处理response body的字段body_filter_by_lua_file,然后在该入口内处理你的逻辑,在这里我这的大概逻辑是解码,解压缩,处理异常,然后把数据写到日志
处理流程
在配置文件你要处理的server中添加
#conf/lua/get_resp.lua:相对路径下的lua处理文件
body_filter_by_lua_file conf/lua/get_resp.lua;
# 设置日志变量
set $resp_code '';
set $resp_msg '';
下载zlib库 点我下载
wget https://github.com/hamishforbes/lua-ffi-zlib
编写逻辑代码
local json = require "cjson"
local zlib = require 'ffi-zlib'
``
function json_decode(str)
local data = nil
_, err = pcall(function(str) return json.decode(str) end, str)
return data, err
end
local chunk = string.sub(ngx.arg[1], 1, 1000)
ngx.ctx.buffered = (ngx.ctx.buffered or "") .. chunk
if ngx.arg[2] then
--ngx.ctx.buffered获取到response body的压缩数据 compressed = ngx.ctx.buffered
output_table = {}
local chk = 16384
local input = function(bufsize)
local start = count > 0 and bufsize*count or 1
local data = compressed:sub(start, (bufsize* (count+1)-1))
count = count + 1
return data
end
local output = function(data)
table_insert(output_table, data)
end
local ok, err = zlib.inflateGzip(input, output, chk)
if not ok then
ngx.log(ngx.ERR,'decompress err:'..err)
return
end
local output_data = table_concat(output_table,'')
--ngx.log(ngx.ERR,'decompress res:'..output_data)
local err,data = json_decode(output_data)
if err then
ngx.log(ngx.ERR,'compress decode err:'..err)
end
-- data就是需要的table数据
-- 这里也需要做异常判断,你自己加就好了
ngx.var.resp_code = data['code']
ngx.var.resp_msg = data['msg']
end