https://kotlinlang.org logo
Title
m

Matthieu Stombellini

08/09/2021, 10:52 AM
Hello! I'm trying to implement a feature that sends a HTTP 301 redirection when certain paths are requested, but nothing has matched them in the routing step (note that I'm building general-purpose redirection feature, so just putting those paths directly in the
routing {}
block is not an option). It seems that intercepting the
Fallback
pipeline would be a good solution, but it turns out that a response is already sent earlier in that pipeline by default due to this code: https://github.com/ktorio/ktor/blob/066d0c4f12debb32b3e7385ca07c4f1bd767e0a4/ktor-[…]t-common/jvm/src/io/ktor/server/engine/BaseApplicationEngine.kt, thus triggering a ResponseAlreadySentException when I try to call
call.respond(...)
in my interceptor. Is there anyway to intercept the pipeline before the default interceptors kick in, or if not, which phase should I intercept?
a

Aleksei Tirman [JB]

08/09/2021, 11:13 AM
You can add a phase before the
Fallback
phase and intercept it to respond before default fallback interceptor:
val phase = PipelinePhase("my phase")
insertPhaseBefore(ApplicationCallPipeline.Fallback, phase)
intercept(phase) {
    call.respond(HttpStatusCode.MovedPermanently)
}
m

Matthieu Stombellini

08/09/2021, 11:17 AM
Ooh, I didn't think of that, thank you very much!