kemal/src/kemal/route_handler.cr

53 lines
1.6 KiB
Crystal
Raw Normal View History

2016-01-24 18:50:54 +00:00
require "radix"
2014-06-11 23:41:02 +00:00
2016-07-17 11:43:13 +00:00
module Kemal
# Kemal::RouteHandler is the main handler which handles all the HTTP requests. Routing, parsing, rendering e.g
# are done in this handler.
class RouteHandler < HTTP::Handler
INSTANCE = new
2016-07-17 11:43:13 +00:00
property tree
2016-07-17 11:43:13 +00:00
def initialize
@tree = Radix::Tree(Route).new
end
2014-06-11 23:41:02 +00:00
2016-07-17 11:43:13 +00:00
def call(context)
process_request(context)
end
2014-06-11 23:41:02 +00:00
2016-07-17 11:43:13 +00:00
# Adds a given route to routing tree. As an exception each `GET` route additionaly defines
# a corresponding `HEAD` route.
def add_route(method, path, &handler : HTTP::Server::Context -> _)
add_to_radix_tree method, path, Route.new(method, path, &handler)
add_to_radix_tree("HEAD", path, Route.new("HEAD", path, &handler)) if method == "GET"
end
2014-06-11 23:41:02 +00:00
2016-07-17 11:43:13 +00:00
# Check if a route is defined and returns the lookup
def lookup_route(verb, path)
@tree.find radix_path(verb, path)
end
2016-07-17 11:43:13 +00:00
# Processes the route if it's a match. Otherwise renders 404.
def process_request(context)
raise Kemal::Exceptions::RouteNotFound.new(context) unless context.route_defined?
route = context.route_lookup.payload.as(Route)
content = route.handler.call(context)
if Kemal.config.error_handlers.has_key?(context.response.status_code)
raise Kemal::Exceptions::CustomException.new(context)
end
context.response.print(content)
context
2016-05-05 19:35:36 +00:00
end
2016-07-17 11:43:13 +00:00
private def radix_path(method : String, path)
"/#{method.downcase}#{path}"
end
2016-07-17 11:43:13 +00:00
private def add_to_radix_tree(method, path, route)
node = radix_path method, path
@tree.add node, route
end
end
2014-06-11 23:41:02 +00:00
end