kotlin - 如何在 Ktor 中获取 call.response 的 http body?

标签 kotlin ktor

我用 Ktor 构建了一个 Web 服务器,并且想要缓存 API 方法结果。但我不知道如何从 call.response 获取响应正文。代码如下

fun Application.module(){

    // before method was called
    intercept(ApplicationCallPipeline.Features) {
        val cache = redis.get("cache")
        if(cache) {
            call.respond(cache)
        }

        return @intercept finish()
    }
    
    // after method was called
    intercept(ApplicationCallPipeline.Fallback) {
        // TODO, how to get call.response.body
        redis.set("cache", call.response.body)
    }
}

如果我无法获取响应正文,还有其他解决方案可以在 Ktor 中缓存 API 方法的结果吗?

最佳答案

在拦截器内,对于 ApplicationCallPipeline.Features 阶段,您可以在 ApplicationSendPipeline.Engine 之前添加一个阶段,并拦截它以检索响应正文 (内容):

val phase = PipelinePhase("phase")
call.response.pipeline.insertPhaseBefore(ApplicationSendPipeline.Engine, phase)
call.response.pipeline.intercept(phase) { response ->
    val content: ByteReadChannel = when (response) {
        is OutgoingContent.ByteArrayContent -> ByteReadChannel(response.bytes())
        is OutgoingContent.NoContent -> ByteReadChannel.Empty
        is OutgoingContent.ReadChannelContent -> response.readFrom()
        is OutgoingContent.WriteChannelContent -> GlobalScope.writer(coroutineContext, autoFlush = true) {
            response.writeTo(channel)
        }.channel
        else -> error("")
    }

    // Do something with content
}

关于kotlin - 如何在 Ktor 中获取 call.response 的 http body?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70272721/

相关文章:

android - 撰写错误 - 导入后 "Unresolved reference: align"

kotlin - 如何在带有ktor框架的graphql-kotlin中进行字段级解析器

android - 编译器无法解析 io.ktor.client.features.logging 中的类

json - ktor 为某些数据类抛出 NoTransformationFoundException

authentication - 有没有办法在不使用其 UI 的情况下使用 KeyCloak 身份验证?

spring-boot - 在Kotlin中将@ConfigurationProperties与嵌套属性一起使用

android - Kotlin ViewModel 类中预期的属性 getter 或 setter

android - Kotlin Unresolved reference

android - android studio IDE中的Kotlin编译器预发布问题

kotlin - 在 Ktor 应用程序模块而不是 Main 中获取命令行参数?