Can a Ktor plugin inject a `CoroutineContext` elem...
# ktor
c
Can a Ktor plugin inject a
CoroutineContext
element into the rest of the pipeline?
a
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
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