2016-07-17 11:43:13 +00:00
|
|
|
module Kemal
|
2017-09-10 11:41:07 +00:00
|
|
|
class WebSocketHandler
|
|
|
|
include HTTP::Handler
|
2018-03-17 14:58:19 +00:00
|
|
|
|
2017-09-10 11:41:07 +00:00
|
|
|
INSTANCE = new
|
2017-10-06 09:46:58 +00:00
|
|
|
property routes
|
2017-09-10 11:41:07 +00:00
|
|
|
|
|
|
|
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)
|
2017-09-14 16:59:22 +00:00
|
|
|
return call_next(context) unless context.ws_route_defined? && websocket_upgrade_request?(context)
|
2017-09-10 11:41:07 +00:00
|
|
|
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}"
|
2017-09-10 11:41:07 +00:00
|
|
|
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)
|
2017-09-10 11:41:07 +00:00
|
|
|
end
|
|
|
|
|
2017-10-06 09:46:58 +00:00
|
|
|
private def add_to_radix_tree(path, websocket)
|
2017-09-10 11:41:07 +00:00
|
|
|
node = radix_path "ws", path
|
2017-10-06 09:46:58 +00:00
|
|
|
@routes.add node, websocket
|
2017-09-10 11:41:07 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
private def radix_path(method, path)
|
|
|
|
"/#{method.downcase}#{path}"
|
2016-07-17 11:43:13 +00:00
|
|
|
end
|
2017-09-14 16:59:22 +00:00
|
|
|
|
|
|
|
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
|