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
|
|
|
|
|
2016-02-16 20:07:58 +00:00
|
|
|
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-06-19 00:22:55 +00:00
|
|
|
context.response.headers.add "X-Powered-By", "Kemal"
|
2016-05-14 08:07:19 +00:00
|
|
|
context.response.content_type = "text/html" unless context.response.headers.has_key?("Content-Type")
|
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 -> _)
|
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-16 20:07:58 +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-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)
|
2016-05-05 20:22:58 +00:00
|
|
|
raise Kemal::Exceptions::RouteNotFound.new(context) unless context.route_defined?
|
2016-06-15 05:58:14 +00:00
|
|
|
route = context.route_lookup.payload.as(Route)
|
2016-05-05 20:22:58 +00:00
|
|
|
content = route.handler.call(context)
|
2016-05-05 19:35:36 +00:00
|
|
|
if Kemal.config.error_handlers.has_key?(context.response.status_code)
|
2016-05-05 20:22:58 +00:00
|
|
|
raise Kemal::Exceptions::CustomException.new(context)
|
2016-05-05 19:35:36 +00:00
|
|
|
end
|
2016-05-05 20:22:58 +00:00
|
|
|
context.response.print(content)
|
2016-02-14 10:43:25 +00:00
|
|
|
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
|