Client Closing keep-alive connections

I am writing a custom plugin for kong . The plugin will transform request/response in accordance with my server. I am getting [info] 27#0: *588 client <x> closed keepalive connection .

After some debugging, I found that the error occurs whenever I set the ngx.arg[1] with my transformed response. I have followed the existing response-transformer plugin provided by kong.

This is the body of the kong body_filter function:

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 someChunks = concat(ctx.rt_body_chunks)
    local aBody = responseTransformer.transform(theConf, someChunks)
    aBody = unEscapeString(aBody)
    ngx.arg[1] = aBody or someChunks
    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

I ran the same plugin with a local dummy server. It worked properly. But when I proxied to my actual server, I got the closed keepalive connection error.

From kong logs, I can see that the response got transformed properly.

Using curl , I get about half the body of the response.

Found the cause. The server was sending Content-Length header. During rewrite of body this remained unchanged. So, connection was being closed before the full content was being delivered.

To solve this, I had to clear the Content-Length header in the header_filter function: