suspend fun dumpRequest()

in runtime/protocol/http/common/src/aws/smithy/kotlin/runtime/http/request/HttpRequestBuilder.kt [76:113]


suspend fun dumpRequest(request: HttpRequestBuilder, dumpBody: Boolean): String {
    val buffer = SdkByteBuffer(256u)

    // TODO - we have no way to know the http version at this level to set HTTP/x.x
    buffer.write("${request.method} ${request.url.encodedPath}\r\n")
    buffer.write("Host: ${request.url.host}\r\n")

    val contentLength = request.headers["Content-Length"]?.toLongOrNull() ?: (request.body.contentLength ?: 0)
    if (contentLength > 0) {
        buffer.write("Content-Length: $contentLength\r\n")
    }

    val skip = setOf("Host", "Content-Length")
    request.headers.entries()
        .filterNot { it.key in skip }
        .forEach {
            buffer.write(it.value.joinToString(separator = ";", prefix = "${it.key}: ", postfix = "\r\n"))
        }

    buffer.write("\r\n")

    if (dumpBody) {
        when (val body = request.body) {
            is HttpBody.Bytes -> buffer.writeFully(body.bytes())
            is HttpBody.Streaming -> {
                // consume the stream and replace the body
                val content = body.readAll()
                if (content != null) {
                    buffer.writeFully(content)
                    request.body = ByteArrayContent(content)
                }
            }
            is HttpBody.Empty -> { } // nothing to dump
        }
    }

    return buffer.decodeToString()
}