Kong插件开发-重写响应消息体

本篇文章主要讲述如何通过 kong 插件重写响应给客户端的消息体内容,以下内容基于 kong v1.4.x 版本,官方文档

按照官方文档,可以通过以下指令来重写返回给客户端的消息体,但只有在特定阶段才能重写

1
2
3
4
kong.response.exit(status[, body[, headers]])

Phase:
rewrite, access, admin_api, header_filter (only if body is nil)

假设我们的需求是当收到 Upstream 返回失败时(Http Status Code >= 400 )修改返回客户端的响应体,使用 kong pdk 中的接口都会提示执行错误,因为 header_filter 以及以后的阶段是不能直接修改的。

但我们可以通过执行 ngx 的一些指令来实现这个操作,该用法出现在 kong 官方插件 response-transformer 中,经过测试,可以满足该需求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
local kong = kong
local ngx = ngx
local concat = table.concat

# 因为会修改返回的响应体内容,所以要去掉此 header
kong.response.clear_header("Content-Length")

# 修改返回给调用端的响应体内容
local ctx = ngx.ctx
local chunk, eof = ngx.arg[1], ngx.arg[2]

ctx.rt_body_chunks = ctx.rt_body_chunks or {}
ctx.rt_body_chunk_number = ctx.rt_body_chunk_number or 1

if eof then
local chunks = concat(ctx.rt_body_chunks)
local body = responseBody
ngx.arg[1] = body or chunks
else
ctx.rt_body_chunks[ctx.rt_body_chunk_number] = chunk
ctx.rt_body_chunk_number = ctx.rt_body_chunk_number + 1
ngx.arg[1] = nil
end
#
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×