A websocket HTTP Channel.
Channel instance is bind to a websocket instance, calling
on according socket event. You are expected to re-define these methods.
Channel includes the
Channel params can be defined with the
Endpoint.params macro. The params are
checked before the request is upgraded to a websocket, raising a default 400
HTTP error if something is wrong.
Channel errors can be defined with the
Endpoint.errors macro. They can be raised
when the request is not upgraded yet (by overriding default
#call method or in callbacks),
or when it is already a websocket.
Some considertations when raising when already upgraded:
- Error codes must be in 4000-4999 range to conform with standards
- Error message length must be less than or equal to 123 characters
HTTP::Errors are rescued and handled internally in a
Channel, properly closing the socket, so you do not need a rescuer there
class Channels::Echo include Onyx::HTTP::Channel params do query do # Would raise 400 HTTP error before upgrading if username is missing type username : String # Would raise 400 HTTP error before upgrading if secret is missing or of invalid type type secret : Int32 end end errors do # Expected to be raised before the request is upgraded type UsernameTaken(403) # Expected to be raised when the request is already upgraded to a websocket type InvalidSecret(4003) end before do # Return 403 HTTP error without upgrading to a websocket raise UsernameTaken.new if params.query.username == "Vlad" end def on_open unless params.query.secret == 42 # Close websocket with 4003 code and "Invalid Secret" reason raise InvalidSecret.new end end def on_message(message) socket.send(message) end end
router = Onyx::HTTP::Router.new do |r| r.ws "/", Channels::Echo # Equivalent of r.ws "/" do |context| channel.call(context) end end
Class Method Summary
Instance Method Summary
Called when the socket receives a binary message from client.