kemal/src/kemal/websocket_handler.cr

39 lines
1.1 KiB
Crystal
Raw Normal View History

2016-07-17 11:43:13 +00:00
module Kemal
# Kemal::WebSocketHandler is used for building a WebSocket route.
# For each WebSocket route a new handler is created and registered to global handlers.
class WebSocketHandler
include HTTP::Handler
INSTANCE = new
property ws_routes
def initialize
@ws_routes = Radix::Tree(WebSocket).new
2016-07-17 11:43:13 +00:00
end
2015-12-15 21:11:21 +00:00
2017-08-25 13:41:02 +00:00
def call(context : HTTP::Server::Context)
2017-08-20 17:10:38 +00:00
return call_next(context) unless context.ws_route_defined?
context.request.url_params ||= context.ws_route_lookup.params
content = context.websocket.call(context)
context.response.print(content)
context
end
def lookup_ws_route(path : String)
@ws_routes.find "/ws#{path}"
end
def add_ws_route(path : String, &handler : HTTP::WebSocket, HTTP::Server::Context -> Void)
add_to_ws_radix_tree path, WebSocket.new(path, &handler)
end
private def add_to_ws_radix_tree(path, websocket)
node = radix_path "ws", path
@ws_routes.add node, websocket
end
private def radix_path(method, path)
"/#{method.downcase}#{path}"
2016-07-17 11:43:13 +00:00
end
2015-12-15 21:11:21 +00:00
end
end