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

CLOVIS

01/15/2023, 4:42 PM
Can a Ktor plugin inject a
CoroutineContext
element into the rest of the pipeline?
a

Aleksei Tirman [JB]

01/16/2023, 10:53 AM
You have to intercept a pipeline directly to do that. Here is an example:
Copy code
class MyElement : CoroutineContext.Element {
    override val key: CoroutineContext.Key<*>
        get() = MyElement

    companion object : CoroutineContext.Key<MyElement>
}

fun main() {
    embeddedServer(Netty, host = "0.0.0.0", port = 12345) {
        sendPipeline.intercept(ApplicationSendPipeline.Before) {
            withContext(coroutineContext + MyElement()) {
                proceed()
            }
        }

        sendPipeline.intercept(ApplicationSendPipeline.Transform) {
            println(coroutineContext[MyElement])
        }

        routing {
            get("/") {
                call.respondText { "OK" }
            }
        }
    }.start(wait = true)
}
c

CLOVIS

01/16/2023, 11:38 AM
Thanks!
It seems to me like
ApplicationSendPipeline.Before
is executed after
call.respondText
… which pipeline stage should I use for the context to be available in the route code?
ApplicationCallPipeline.Plugins
seems to do the trick
7 Views