module Onyx::HTTP::Channel

Overview

A websocket HTTP Channel.

Channel instance is bind to a websocket instance, calling #on_open, #on_message, #on_binary, #on_ping, #on_pong and #on_close callbacks on according socket event. You are expected to re-define these methods.

Channel includes the Endpoint module.

Params

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.

Errors

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:

Example

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 example:

router = Onyx::HTTP::Router.new do
  ws "/", Channels::Echo
  # Equivalent of
  ws "/" do |context|
    channel.call(context)
  end
end

Included Modules

Defined in:

onyx-http/channel.cr

Class Method Summary

Instance Method Summary

Instance methods inherited from module Onyx::HTTP::Endpoint

after after, before before, call call, view(view : View) view

Constructor methods inherited from module Onyx::HTTP::Endpoint

new(context : HTTP::Server::Context) new

Class Method Detail

def self.call(context) #

[View source]

Instance Method Detail

def call #

By default calls #upgrade, which upgrades the request to a websocket and then calls #bind.


[View source]
def on_binary(binary) #

Called when the socket receives a binary message from client.


[View source]