Hello! How can i read request body in MockEngine h...
# ktor
a
Hello! How can i read request body in MockEngine handler?
a
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
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
If you know the type of a
OutgoingContent
in advance then you can just cast
request.body
to that type.
a
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
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
Ok, thank you