kemal/src/kemal/handler.cr

43 lines
1.1 KiB
Crystal
Raw Normal View History

2014-12-14 12:08:16 +00:00
require "http/server"
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
@routes = [] of Route
end
def call(request)
response = process_request(request)
response || call_next(request)
2014-06-11 23:41:02 +00:00
end
2015-10-23 18:33:26 +00:00
def add_route(method, path, &handler : Kemal::Context -> _)
@routes << Route.new(method, path, &handler)
# Registering HEAD route for defined GET routes.
@routes << Route.new("HEAD", path, &handler) if method == "GET"
2014-06-11 23:41:02 +00:00
end
2015-11-17 19:43:05 +00:00
def process_request(request)
2016-01-12 19:37:12 +00:00
url = request.path.not_nil!
2014-06-11 23:41:02 +00:00
@routes.each do |route|
if route.match?(request)
2016-01-12 19:37:12 +00:00
context = Context.new(request, route)
begin
body = route.handler.call(context).to_s
2015-10-30 20:34:44 +00:00
return HTTP::Response.new(context.status_code, body, context.response_headers)
rescue ex
2016-01-04 19:54:58 +00:00
Kemal::Logger::INSTANCE.write "Exception: #{ex.to_s}\n"
2015-11-29 15:32:31 +00:00
return render_500(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
return render_404
2014-06-11 23:41:02 +00:00
end
end