Alexander Zhirkevich
11/12/2025, 1:27 PMHristijan
11/12/2025, 1:36 PMAlexander Zhirkevich
11/12/2025, 1:53 PMHristijan
11/12/2025, 11:17 PMHristijan
11/12/2025, 11:18 PMAleksei Tirman [JB]
11/13/2025, 7:32 AMfun Route.webSocketWithHeaders(path: String, headers: Headers, block: suspend WebSocketServerSession.() -> Unit) {
route(path) {
header(HttpHeaders.Connection, "Upgrade") {
header(HttpHeaders.Upgrade, "websocket") {
get {
headers.forEach { name, values ->
call.response.headers.appendIfAbsent(name, values.joinToString(separator = ", "))
}
call.respond(WebSocketUpgrade(call, null, installExtensions = true, {
val session = toServerSession(call)
session.block()
}))
}
}
}
}
}
private fun WebSocketSession.toServerSession(call: ApplicationCall): WebSocketServerSession =
DelegatedWebSocketServerSession(call, this)
private fun DefaultWebSocketSession.toServerSession(call: ApplicationCall): DefaultWebSocketServerSession =
DelegatedDefaultWebSocketServerSession(call, this)
private class DelegatedWebSocketServerSession(
override val call: ApplicationCall,
val delegate: WebSocketSession
) : WebSocketServerSession, WebSocketSession by delegate
private class DelegatedDefaultWebSocketServerSession(
override val call: ApplicationCall,
val delegate: DefaultWebSocketSession
) : DefaultWebSocketServerSession, DefaultWebSocketSession by delegate
Here is how it can be used:
routing {
webSocketWithHeaders("/ws", Headers.build {
append(HttpHeaders.SetCookie, "name=value; path=/")
}) {
outgoing.send(Frame.Text("Hello World!"))
}
}Alexander Zhirkevich
11/13/2025, 7:36 AMfun Route.customRoute(path : String){
route(path, HttpMethod.Get) {
header(HttpHeaders.Connection, "Upgrade") {
header(HttpHeaders.Upgrade, "websocket") {
handle {
call.response.headers.append()
}
}
}
}
webSocket(path) {
// ...
}
}