Hey there. How can I run logic before a websocket ...
# ktor
m
Hey there. How can I run logic before a websocket connection is established? I’d like to validate URL parameters before the websocket session starts so that I can return 404 for invalid parameters for example. The only way I can think of is using
install()
to intercept the call.
a
You can use a similar solution to what was discussed here. Here is an example:
Copy code
fun main() {
    embeddedServer(Jetty, port = 8090) {
        install(WebSockets)
        routing {
            validateURLParams {
                webSocket("/") {
                    send(Frame.Text("hello"))

                    for (msg in incoming) {
                        println((msg as Frame.Text).readText())
                    }
                }
            }
        }
    }.start(true)
}

fun Route.validateURLParams(build: Route.() -> Unit): Route {
    val route = createChild(MyRouteSelector())
    route.intercept(ApplicationCallPipeline.Features) {
        // if (!parametersValid()) {
            call.respond(HttpStatusCode.NotFound)
            finish()
        // }
    }

    route.build()
    return route
}

class MyRouteSelector : RouteSelector() {
    override fun evaluate(context: RoutingResolveContext, segmentIndex: Int): RouteSelectorEvaluation {
        return RouteSelectorEvaluation(true, RouteSelectorEvaluation.qualityTransparent)
    }
}
m
Thanks. That’s more or less the same approach as installing something into the route. Pipeline interceptor in both cases. This is the solution I came up with by now:
a
Why do you need a feature here? Can't you just intercept the
ApplicationCallPipeline
?
m
Maybe. Haven’t tried 😄
a
I think you can get rid of a feature and its installation as they just add a noise
m
Will check soon 🙂