I'm building a microservice in Ktor. While we are working within the application module, Ktor provides access to the call object which contains authorization data.
My problem is that I need to access the call object from a service-level class. In Spring, you would do this by accessing the SecurityContext which is globally available via a ThreadLocal. Ktor, being coroutine-driven, does not have that option.
Do I really need to pass down the call object through my service layer methods, or is there a way in Ktor to have some sort of "call context" object that you can access from anywhere?
I think there is no build-in official opportunity at the moment.
I have written a Ktor-Feature, that implements that behaviour. The answer is to complicated to describe it in a few words.
Check out the code + samples, if you are interested. Also an install guide is provided.
=> https://github.com/MaaxGr/ktor-globalcalldata
Call suspending function test() directly or indirectly from a route:
routing {
get("/test") {
test()
call.respond("OK")
}
}
Access call object via callData().call
suspend fun test() {
val url = callData().call.request.uri
println(url) // prints "/test"
}
The library also allows to add custom properties that can be bound to the current coroutine/call.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With