Home > database >  Adding interceptor to routes in Ktor not working
Adding interceptor to routes in Ktor not working

Time:12-10

I have a Route where for every ApplicationCall I'd like to add a header to the response.

e.g.

routes {
   route("/cdn-cached") {
        intercept(ApplicationCallPipeline.Features){
           call.response.header(HttpHeaders.CacheControl, ...)
        }
        

        get(...) {...}
        post(...) {...}
        route(...) {...}
   }
}

This is an oversimplified example of a setup I have, but what I expect is that every time I call an endpoint under the /cdn-cached route it gets the header attached. I am sure I mess up something, but I don't know what.

What do I need to fix this code?

Note: I have a framework that does a lot of dynamic things, so far it could do everything I wanted, now I got stumbled on this one. I just tell this because it is not a good option for me to add the header in every individual ApplicationCall like the get, post and route here. I could do that, but I'd prefer not to if I can just do it similarly to what I described in the example.

CodePudding user response:

You can intercept the ApplicationCallPipeline.Call phase to affect current route and its child routes:

route("/cdn-cached") {
    intercept(ApplicationCallPipeline.Call) {
        call.response.header("custom", "123")
    }

    // ...
}
  • Related