class Athena::Routing::RoutingHandler

Overview

Provides basic routing functionality to an HTTP::Server.

This type works as both a HTTP::Handler and an ART::RouteCollection that accepts a block that will handle that particular route.

handler = ART::RoutingHandler.new

# The `methods` property can be used to limit the route to a particular HTTP method.
handler.add "new_article", ART::Route.new("/article", methods: "post") do |ctx|
  pp ctx.request.body.try &.gets_to_end
end

# The match parameters from the route are passed to the callback as a `Hash(String, String?)`.
handler.add "article", ART::Route.new("/article/{id<\\d+>}", methods: "get") do |ctx, params|
  pp params # => {"_route" => "article", "id" => "10"}
end

# Call the `#compile` method when providing the handler to the handler array.
server = HTTP::Server.new([
  handler.compile,
])

address = server.bind_tcp 8080
puts "Listening on http://#{address}"
server.listen

NOTE This handler should be the last one, as it is terminal.

Bubbling Exceptions

By default, requests that result in an exception, either from Athena::Routing or the callback block itself, are gracefully handled by returning a proper error response to the client via HTTP::Server::Response#respond_with_status.

You can set bubble_exceptions: true when instantaintg the routing handler to have full control over the returned response. This would allow you to define your own HTTP::Handler that can rescue the exceptions and apply your custom logic for how to handle the error.

class ErrorHandler
  include HTTP::Handler

  def call(context)
    call_next context
  rescue ex
    # Do something based on the ex, such as rendering the appropriate template, etc.
  end
end

handler = ART::RoutingHandler.new bubble_exceptions: true

# Add the routes...

# Have the `ErrorHandler` run _before_ the routing handler.
server = HTTP::Server.new([
  ErrorHandler.new,
  handler.compile,
])

address = server.bind_tcp 8080
puts "Listening on http://#{address}"
server.listen

Included Modules

Defined in:

routing_handler.cr

Constructors

Instance Method Summary

Constructor Detail

def self.new(matcher : ART::Matcher::URLMatcherInterface | Nil = nil, collection : ART::RouteCollection = ART::RouteCollection.new, bubble_exceptions : Bool = false) #

[View source]

Instance Method Detail

def add(name : String, route : ART::Route, priority : Int32 = 0, &block : HTTP::Server::Context, Hash(String, String | Nil) -> Nil) : Nil #

Adds the provided route with the provided name to this collection, optionally with the provided priority. The passed block will be called when a request matching this route is encountered.


[View source]
def call(context) #

:inherit:


[View source]
def compile : self #

Helper method that calls ART.compile with the internal ART::RouteCollection, and returns self to make setting up the routes easier.

handler = ART::RoutingHandler.new

# Register routes

server = HTTP::Server.new([
  handler.compile,
])

[View source]