Skip to content

class Athena::Routing::RoutingHandler
inherits Reference #

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.

Included modules

HTTP::Handler

Constructors#

.new(matcher : ART::Matcher::URLMatcherInterface? = nil, collection : ART::RouteCollection = ART::RouteCollection.new)#

View source

Methods#

#add(name : String, route : ART::Route, priority : Int32 = 0, &block : HTTP::Server::Context, Hash(String, String?) -> 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

#call(context)#

:inherit:

View source

#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