https://kotlinlang.org logo
#ktor
Title
# ktor
v

Vinicius Carvalho

03/26/2019, 2:58 PM
Hi folks, I think the docs at https://ktor.io/advanced/pipeline/route.html could get some better explanation on the whole interception of a route. reading the section:
How to intercept preventing additional executions
its not clear where that
intercept
function belongs to. Could someone care to explain how to add an interceptor to any route that could prevent the pipeline to continue (verifying a header)
m

Michael Pearce

03/27/2019, 4:25 AM
I was getting lost trying to do something similar. I ended up with the following extension function:
Copy code
fun Route.requireHeaders(vararg headerNames: String) {
    intercept(ApplicationCallPipeline.Call) {
        val request = call.request
        headerNames.forEach { requiredHeader ->
            if (request.header(requiredHeader) == null) {
                call.respond(HttpStatusCode.BadRequest)
                finish()
                return@intercept
            }
        }
    }
}
And then used it in the routes like:
Copy code
route("/some_path") {
        requireHeaders("X-Some-Header", "X-Some-Other-Header")
        get { call.respond(...) }
    }
7 Views