https://kotlinlang.org logo
#ktor
Title
# ktor
a

Alexander Sysoev

07/20/2022, 2:35 PM
Hello! How can i read request body in MockEngine handler?
a

Aleksei Tirman [JB]

07/20/2022, 3:57 PM
You can determine what type of a
OutgoingContent
you’re dealing with to convert it to a
ByteReadChannel
and then read bytes from the channel:
Copy code
val client = HttpClient(MockEngine) {
    engine {
        addHandler { request ->
            val content: ByteReadChannel = when (val body = request.body) {
                is OutgoingContent.ByteArrayContent -> ByteReadChannel(body.bytes())
                is OutgoingContent.NoContent -> ByteReadChannel.Empty
                is OutgoingContent.ReadChannelContent -> body.readFrom()
                is OutgoingContent.WriteChannelContent -> GlobalScope.writer(coroutineContext, autoFlush = true) {
                    body.writeTo(channel)
                }.channel
                else -> error("Not supported OutgoingContent type")
            }

            // Use content.readRemaining().readText() to read body as String

            respondOk()
        }
    }
}
a

Alexander Sysoev

07/20/2022, 4:18 PM
It worked, thank you! But i dont understand why, i have
WriteChannelContent
, why do i need such complicated and unobvious way to read it?
a

Aleksei Tirman [JB]

07/20/2022, 4:51 PM
If you know the type of a
OutgoingContent
in advance then you can just cast
request.body
to that type.
a

Alexander Sysoev

07/20/2022, 4:53 PM
Yeah, i mean, i know that it is WriteChannel, but why do i need GlobalScope.writer etc to read from it?
Why extension function .toByteArray() does not work? It just hangs
a

Aleksei Tirman [JB]

07/20/2022, 4:55 PM
Because the
WriteChannelContent
can only write data to a
ByteWriteChannel
.
Copy code
public abstract class WriteChannelContent : OutgoingContent() {
    public abstract suspend fun writeTo(channel: ByteWriteChannel)
}
You can’t directly get a
ByteReadChannel
or a
ByteArray
using this class.
a

Alexander Sysoev

07/20/2022, 4:57 PM
Ok, thank you
11 Views