annotation

Kemal::Controller::WebSocket

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

  • path : String - The URL path for the route (can include path parameters like :id)
  • auth : Bool - If true, requires authentication via authenticate! method (default: false)
  • strip : Bool | Array(Symbol) - If true, strips all parameters; if array, strips only specified parameters (default: false)

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