Skip to content

Commit

Permalink
feat: support limit_size field to the hold_body_chunk method to trunc…
Browse files Browse the repository at this point in the history
…ate response_body (apache#5915)
  • Loading branch information
kyroslin committed Jan 5, 2022
1 parent d3bb8f9 commit f0f6717
Showing 1 changed file with 29 additions and 1 deletion.
30 changes: 29 additions & 1 deletion apisix/core/response.lua
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,19 @@ function _M.clear_header_as_body_modified()
ngx.header.etag = nil
end

local function check_limit_size(ctx, body_buffer_size, limit_size)
if not limit_size then
return
end

if body_buffer_size > limit_size then
ctx._body_buffer = nil
ctx._body_hold_flag = true
else
ctx._body_buffer_size = body_buffer_size
ctx._body_hold_flag = false
end
end

-- Hold body chunks and return the final body once all chunks have been read.
-- Usage:
Expand All @@ -164,11 +177,17 @@ end
-- final_body = transform(final_body)
-- ngx.arg[1] = final_body
-- ...
function _M.hold_body_chunk(ctx, hold_the_copy)
function _M.hold_body_chunk(ctx, hold_the_copy, limit_size)
local body_buffer_size, body_hold_flag
local body_buffer
local chunk, eof = arg[1], arg[2]
if eof then
body_buffer = ctx._body_buffer
body_hold_flag = ctx._body_hold_flag
if body_hold_flag then
return nil
end

if not body_buffer then
return chunk
end
Expand All @@ -179,17 +198,26 @@ function _M.hold_body_chunk(ctx, hold_the_copy)
end

if type(chunk) == "string" and chunk ~= "" then
body_hold_flag = ctx._body_hold_flag
if body_hold_flag then
return nil
end

body_buffer = ctx._body_buffer
if not body_buffer then
body_buffer = {
chunk,
n = 1
}
ctx._body_buffer_size = #chunk
ctx._body_buffer = body_buffer
check_limit_size(ctx, #chunk, limit_size)
else
local n = body_buffer.n + 1
body_buffer.n = n
body_buffer[n] = chunk
body_buffer_size = ctx._body_buffer_size + #chunk
check_limit_size(ctx, body_buffer_size, limit_size)
end
end

Expand Down

0 comments on commit f0f6717

Please sign in to comment.