2014-12-14 12:08:16 +00:00
|
|
|
require "http/server"
|
2016-01-22 20:14:22 +00:00
|
|
|
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
|
2014-07-30 22:27:25 +00:00
|
|
|
INSTANCE = new
|
|
|
|
|
2014-06-11 23:41:02 +00:00
|
|
|
def initialize
|
2016-01-22 20:14:22 +00:00
|
|
|
@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 -> _)
|
2016-01-22 20:14:22 +00:00
|
|
|
add_to_radix_tree method, path, Route.new(method, path, &handler)
|
2015-12-03 19:21:22 +00:00
|
|
|
|
|
|
|
# Registering HEAD route for defined GET routes.
|
2016-01-22 20:14:22 +00:00
|
|
|
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)
|
2016-01-22 20:14:22 +00:00
|
|
|
if lookup.found?
|
|
|
|
route = lookup.payload as Route
|
2016-01-24 10:22:25 +00:00
|
|
|
if route.match?(context.request)
|
2014-07-30 23:50:14 +00:00
|
|
|
begin
|
2016-01-24 15:44:37 +00:00
|
|
|
context.response.content_type = "text/html"
|
2014-07-30 23:50:14 +00:00
|
|
|
body = route.handler.call(context).to_s
|
2016-01-24 10:22:25 +00:00
|
|
|
context.response.print body
|
|
|
|
return context
|
2014-07-30 23:50:14 +00:00
|
|
|
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)
|
2014-07-30 23:50:14 +00:00
|
|
|
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
|
2016-01-22 20:14:22 +00:00
|
|
|
|
|
|
|
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
|