kemal/src/kemal/websocket_handler.cr

64 lines
1.6 KiB
Crystal
Raw Normal View History

2016-07-17 11:43:13 +00:00
module Kemal
class WebsocketError < Exception
property code : Int32 = 1011
property status_message : String = "websocket error"
def initialize(@code, @status_message : String)
end
end
class UpgradeRequired < WebsocketError
def initialize
super(426, "Upgrade required")
end
end
class BadRequest < WebsocketError
def initialize(status_message : String)
super(400, status_message)
end
end
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)
2018-08-13 16:21:18 +00:00
return call_next(context) unless context.ws_route_found? && websocket_upgrade_request?(context)
content = context.websocket.call(context)
context.response.print(content)
context
end
def lookup_ws_route(path : String)
2018-11-01 11:29:05 +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)
2018-11-01 11:29:05 +00:00
'/' + method.downcase + path
2016-07-17 11:43:13 +00:00
end
private def websocket_upgrade_request?(context)
2018-11-01 11:29:05 +00:00
return unless upgrade = context.request.headers["Upgrade"]?
return 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