kong 网关插件response-transformer 不处理gzip压缩内容的解决办法

本文介绍了在Kong插件开发中遇到的不处理压缩内容问题,以及如何通过集成zlib库自定义实现压缩和解压缩功能。在Dockerfile中添加zlib环境,并提供lua脚本myCompression.lua来处理gzip压缩。通过对请求头的判断,实现内容的压缩和解压缩操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在插件开发时,发现kong自带插件不处理压缩内容。
需要自己定制开发。

一,使用zlib,新增处理脚本

myCompression.lua

local zlib = require "zlib"
-- see https://stackoverflow.com/questions/45216069/lua-how-to-gzip-a-string-gzip-not-zlib-in-memory
-- and https://github.com/brimworks/lua-zlib


local _M = {}

-- input:  string
-- output: string compressed with gzip
function _M.compress(uncompressed)
    local level = 9
    local windowSize = 15+16
    local stream = zlib.deflate(level, windowSize)
    return stream(uncompressed, "finish")
end

-- input:  string compressed with gzip
-- output: string
function _M.decompress(compressed)
    local stream = zlib.inflate()
    return stream(compressed)
end

return _M

二,使用该上述方法,对hearder进行判断即可

if ngx.header["content-encoding"] == "gzip" then
	decompress(chunks)
then
dosomething...
//记得处理完成后再压缩回去
if ngx.header["content-encoding"] == "gzip" then
	compress(chunks)
then

三,zlib环境安装
zlib使用,需要安装相应环境
在dockerfile中可以用以下代码

RUN /bin/sh -c /bin/sh -c set -ex     \
&& sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories     \
&& apk add --no-cache libuuid     \
&& apk add --no-cache --virtual .build-deps gcc musl-dev zlib-dev     \
&& luarocks install lua-zlib     \
&& apk del .build-deps # buildkit 

以上。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值