kemal/src/kemal/route_handler.cr

49 lines
1.4 KiB
Crystal
Raw Normal View History

2014-12-14 12:08:16 +00:00
require "http/server"
2016-01-24 18:50:54 +00:00
require "radix"
2014-06-11 23:41:02 +00:00
2016-02-03 20:08:54 +00:00
# Kemal::RouteHandler is the main handler which handles all the HTTP requests. Routing, parsing, rendering e.g
2015-12-18 20:45:28 +00:00
# are done in this handler.
2016-02-03 20:08:54 +00:00
class Kemal::RouteHandler < HTTP::Handler
INSTANCE = new
property tree
2014-06-11 23:41:02 +00:00
def initialize
2016-04-12 11:41:09 +00:00
@tree = Radix::Tree(Route).new
2014-06-11 23:41:02 +00:00
end
2016-01-24 10:22:25 +00:00
def call(context)
2016-01-24 15:44:37 +00:00
context.response.content_type = "text/html"
2016-02-14 09:02:16 +00:00
process_request(context)
2014-06-11 23:41:02 +00:00
end
2016-02-14 09:02:16 +00:00
# Adds a given route to routing tree. As an exception each `GET` route additionaly defines
# a corresponding `HEAD` route.
2016-04-12 14:35:29 +00:00
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"
2014-06-11 23:41:02 +00:00
end
# Check if a route is defined and returns the lookup
def lookup_route(verb, path)
@tree.find radix_path(verb, path)
end
2016-02-14 09:02:16 +00:00
# Processes the route if it's a match. Otherwise renders 404.
2016-01-24 10:22:25 +00:00
def process_request(context)
raise Kemal::Exceptions::RouteNotFound.new(context) unless context.route_defined?
route = context.route_lookup.payload as Route
2016-04-12 14:15:43 +00:00
context.response.print(route.handler.call(context))
2016-02-14 10:43:25 +00:00
context
2014-06-11 23:41:02 +00:00
end
private def radix_path(method : String, path)
"/#{method.downcase}#{path}"
end
private def add_to_radix_tree(method, path, route)
node = radix_path method, path
@tree.add node, route
end
2014-06-11 23:41:02 +00:00
end