Can anybody give me a hint, how I can access the a...
# ktor
u
Can anybody give me a hint, how I can access the actual response body in a ktor server plugin within the
ResponseBodyReadyForSend
hook? I have found the
onCallRespond
callback, but I want to be sure, that I get the final response body content which is not further transformed or modified before sent to the client.
a
The second parameter of the handler for
on(ResponseBodyReadyForSend)
is the response body after all transformations.
Copy code
val plugin = createApplicationPlugin("myplugin") {
    on(ResponseBodyReadyForSend) { call, content ->
        println(content)
    }
}
u
The second param is of type
OutgoingContent
which has several properties like
contentType
,
headers
,
status
but none for the response body itself. How doe I get the response body from that content?
a
Since
OutgoingContent
is a sealed class, you can check the actual type and, depending on it, read the body. Here is an example:
Copy code
on(ResponseBodyReadyForSend) { call, content ->
    when(content) {
        is OutgoingContent.ByteArrayContent -> {
            content.bytes() // ByteArray
        }

        is OutgoingContent.ReadChannelContent -> {
            content.readFrom() // ByteReadChannel
        }

        // ...
    }
}
u
Thank you.
one more question: it seems, adding another header within
ResponseBodyReadyForSend
is not possible, because: • adding it to ``call.response.headers` has no effect • modifying
content.headers
is not possible, as
io.ktor.http.Headers
has no methods for appending an header Right?
a
Appending a header through
call.response.headers
should work.
u
yes, that works!