Routing

Routing in Onyx::HTTP is pretty intuitive.

Verbs

There are methods for most HTTP verbs like Onyx.get and Onyx.post. A method expects rither a block with a single HTTP::Server::Context argument (we call it env):

require "onyx/http"

# Will be available at GET /
Onyx.get "/" do |env|
  env.response << "Hello, Onyx!"
end

# Crystal allows to omit blocks' arguments,
# this endpoint will just return 200
Onyx.get "/healthcheck" do
end

WARNING

The proc return value is ignored unless it is a View. For example, this endpoint does not print anything:

Onyx.get "/" do |env|
  "Hello, Onyx!"
end

Or an Endpoint class:

Onyx.get "/", MyEndpoint

Websockets

Websockets are handled a bit differently. There is a special Onyx.ws method, which expects either a block with two arguments: HTTP::WebSocket and HTTP::Server::Context:

# A simple echo endpoint, will be avaialble at ws://host:port/
Onyx.ws "/" do |socket, env|
  socket.on_message do |message|
    socket.send(message)
  end
end

Or a Channel class:

Onyx.ws "/", MyChannel

Path params

You can define path params in routes. These params will then be accessible via context.request.path_params getter:

Onyx.get "/users/:id" do |env|
  env.response << "id = #{env.request.path_params["id"]}"
end
> curl http://localhost:5000/users/42
id = 42

Params can be safely and conveniently parsed in Endpoints and Channels, see their docs for details.

Request ID

The request would also have an unique identifier accessible via context.request.id getter:

Onyx.get "/" do |env|
  pp env.request.id # e6fa3c3e-93ce-4ad4-b480-957cb13b56eb
end