2016-07-17 11:43:13 +00:00
|
|
|
module Kemal
|
2019-06-11 18:38:07 +00:00
|
|
|
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
|
|
|
|
|
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)
|
2018-08-13 16:21:18 +00:00
|
|
|
return call_next(context) unless context.ws_route_found? && websocket_upgrade_request?(context)
|
2020-07-08 11:42:08 +00:00
|
|
|
context.websocket.call(context)
|
2017-09-10 11:41:07 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def lookup_ws_route(path : String)
|
2018-11-01 11:29:05 +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)
|
2018-11-01 11:29:05 +00:00
|
|
|
'/' + 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)
|
2018-11-01 11:29:05 +00:00
|
|
|
return unless upgrade = context.request.headers["Upgrade"]?
|
|
|
|
return unless upgrade.compare("websocket", case_insensitive: true) == 0
|
2017-09-14 16:59:22 +00:00
|
|
|
|
|
|
|
context.request.headers.includes_word?("Connection", "Upgrade")
|
|
|
|
end
|
2015-12-15 21:11:21 +00:00
|
|
|
end
|
|
|
|
end
|