Skip to main content
Version: 4.6.x.x LTS

Add remove or change headers

If you deal with request headers, then we highly recommend that you use Script.InputHeaderFunctionName as this function is called once per request. If you also need to have access to the request body to be able to set a request header, be aware that this is only possible if you have not returned yet a data chunk of the request body.

For the response header, you can only use the streaming function. Also, you have to manipulate the headers before you send back the first data chunk.

We often use the following trick:

firstHit = false
function myHook(request, response, chunk)
if not firstHit then
firstHit = true
-- do here the header magics
end
return chunk
end

This trick guarantees that you will never be too late for header manipulation in a streaming hook.

The example below visualizes how to use the request object methods:

function input(request, response, chunk)
if request:getHeader("Content-Type") == "text/lua" then
if chunk == nil then
body = request:getHeader("Data-Header")
request:setHeader("Content-Length", #body)
return body

else
return chunk
end
end

This simple script triggers body rewriting if the content type is "text/lua". In all other cases, it just returns the received chunks untouched.

In the example, the request body is overwritten by the data stored in the "Data-Header". Also, the content length is adjusted to the new size of the body. In the end, the new body is returned.

Be aware that as long as you do not return body data, you can set/add/remove headers. However, as soon as you return the first chunk of data, you cannot manipulate headers any more.

Usually, you do not receive the body data as one chunk. Therefore, we recommend implementing a sliding window over the body data. This enables you to collect data until you have enough for your task. Only then, return the data.