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
|
2014-07-30 22:27:25 +00:00
|
|
|
INSTANCE = new
|
|
|
|
|
2014-06-11 23:41:02 +00:00
|
|
|
def initialize
|
2016-01-24 18:50:54 +00:00
|
|
|
@tree = Radix::Tree.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-01-24 10:22:25 +00:00
|
|
|
def add_route(method, path, &handler : HTTP::Server::Context -> _)
|
2016-01-22 20:14:22 +00:00
|
|
|
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
|
|
|
|
|
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)
|
|
|
|
Kemal::Route.check_for_method_override!(context.request)
|
2016-01-25 20:22:56 +00:00
|
|
|
lookup = @tree.find radix_path(context.request.override_method as String, context.request.path)
|
2016-02-14 10:43:25 +00:00
|
|
|
raise Kemal::Exceptions::RouteNotFound.new(context) unless lookup.found?
|
|
|
|
route = lookup.payload as Route
|
|
|
|
context.request.url_params = lookup.params
|
|
|
|
context.response.print(route.handler.call(context).to_s)
|
|
|
|
context
|
2014-06-11 23:41:02 +00:00
|
|
|
end
|
2016-01-22 20:14:22 +00:00
|
|
|
|
2016-01-25 20:22:56 +00:00
|
|
|
private def radix_path(method : String, path)
|
|
|
|
"/#{method.downcase}#{path}"
|
2016-01-22 20:14:22 +00:00
|
|
|
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
|