annotation Kemal::Controller::WebSocket

Overview

Annotation to define a WebSocket route for a controller method.

The method is called once, right after the WebSocket handshake completes. Use the socket getter inside the method to register on_message, on_close, etc. handlers. Method parameters are extracted from the handshake request the same way Get does, i.e. from URL/query parameters.

Parameters

NOTE Unlike HTTP routes, by the time a @[WebSocket] method runs the handshake response has already been sent, so auth: true can't reply with a 401, it closes the socket instead (HTTP::WebSocket::CloseCode::PolicyViolation) when authenticate! returns false.

Example

@[WebSocket("/chat/:room")]
def chat(room : String)
  socket.send("Welcome to #{room}!")
  socket.on_message do |message|
    socket.send("#{room}: #{message}")
  end
end

Defined in:

kemal/controller.cr