kemal/src/kemal/websocket_handler.cr

44 lines
1.2 KiB
Crystal
Raw Normal View History

2016-07-17 11:43:13 +00:00
module Kemal
class WebSocketHandler
include HTTP::Handler
2018-03-17 14:58:19 +00:00
INSTANCE = new
2017-10-06 09:46:58 +00:00
property routes
def initialize
2017-10-06 09:46:58 +00:00
@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)
return call_next(context) unless context.ws_route_defined? && websocket_upgrade_request?(context)
content = context.websocket.call(context)
context.response.print(content)
context
end
def lookup_ws_route(path : String)
2017-10-06 09:46:58 +00:00
@routes.find "/ws#{path}"
end
2017-10-02 20:56:02 +00:00
def add_route(path : String, &handler : HTTP::WebSocket, HTTP::Server::Context -> Void)
2017-10-06 09:46:58 +00:00
add_to_radix_tree path, WebSocket.new(path, &handler)
end
2017-10-06 09:46:58 +00:00
private def add_to_radix_tree(path, websocket)
node = radix_path "ws", path
2017-10-06 09:46:58 +00:00
@routes.add node, websocket
end
private def radix_path(method, path)
"/#{method.downcase}#{path}"
2016-07-17 11:43:13 +00:00
end
private def websocket_upgrade_request?(context)
return false unless upgrade = context.request.headers["Upgrade"]?
return false unless upgrade.compare("websocket", case_insensitive: true) == 0
context.request.headers.includes_word?("Connection", "Upgrade")
end
2015-12-15 21:11:21 +00:00
end
end