kemal/src/kemal/handler.cr

58 lines
1.6 KiB
Crystal
Raw Normal View History

2014-12-14 12:08:16 +00:00
require "http/server"
require "beryl/beryl/routing/tree"
2014-06-11 23:41:02 +00:00
2015-12-18 20:45:28 +00:00
# Kemal::Handler is the main handler which handles all the HTTP requests. Routing, parsing, rendering e.g
# are done in this handler.
2015-10-23 18:33:26 +00:00
class Kemal::Handler < HTTP::Handler
INSTANCE = new
2014-06-11 23:41:02 +00:00
def initialize
@tree = Beryl::Routing::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-01-24 10:22:25 +00:00
response = process_request(context)
response || call_next(context)
2014-06-11 23:41:02 +00:00
end
2016-01-24 10:22:25 +00:00
def add_route(method, path, &handler : HTTP::Server::Context -> _)
add_to_radix_tree method, path, Route.new(method, path, &handler)
# Registering HEAD route for defined GET routes.
add_to_radix_tree("HEAD", path, Route.new("HEAD", path, &handler)) if method == "GET"
2014-06-11 23:41:02 +00:00
end
2016-01-24 10:22:25 +00:00
def process_request(context)
url = context.request.path.not_nil!
Kemal::Route.check_for_method_override!(context.request)
lookup = @tree.find radix_path(context.request.override_method, context.request.path)
if lookup.found?
route = lookup.payload as Route
2016-01-24 10:22:25 +00:00
if route.match?(context.request)
begin
2016-01-24 15:44:37 +00:00
context.response.content_type = "text/html"
body = route.handler.call(context).to_s
2016-01-24 10:22:25 +00:00
context.response.print body
return context
rescue ex
2016-01-04 19:54:58 +00:00
Kemal::Logger::INSTANCE.write "Exception: #{ex.to_s}\n"
2016-01-24 10:22:25 +00:00
return render_500(context, ex.to_s)
end
2014-06-11 23:41:02 +00:00
end
end
2015-12-01 19:47:49 +00:00
# Render 404 unless a route matches
2016-01-24 10:22:25 +00:00
return render_404(context)
2014-06-11 23:41:02 +00:00
end
private def radix_path(method, path)
"#{method} #{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