Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make request-bound data globally available in Ktor?

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?

like image 267
Alan47 Avatar asked Dec 06 '25 06:12

Alan47


1 Answers

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


Here a short snippet, what my dsl looks like:

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.

like image 200
Caelis Avatar answered Dec 09 '25 23:12

Caelis