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
|
2014-07-30 22:27:25 +00:00
|
|
|
INSTANCE = new
|
|
|
|
|
2014-06-11 23:41:02 +00:00
|
|
|
def initialize
|
|
|
|
@routes = [] of Route
|
|
|
|
end
|
|
|
|
|
|
|
|
def call(request)
|
2015-11-15 15:00:51 +00:00
|
|
|
response = process_request(request)
|
2014-07-30 23:50:14 +00:00
|
|
|
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 -> _)
|
2014-07-30 22:58:48 +00:00
|
|
|
@routes << Route.new(method, path, &handler)
|
2015-12-03 19:21:22 +00:00
|
|
|
|
|
|
|
# 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|
|
2016-01-13 13:22:50 +00:00
|
|
|
if route.match?(request)
|
2016-01-12 19:37:12 +00:00
|
|
|
context = Context.new(request, route)
|
2014-07-30 23:50:14 +00:00
|
|
|
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)
|
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"
|
2015-11-29 15:32:31 +00:00
|
|
|
return render_500(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
|
|
|
|
return render_404
|
2014-06-11 23:41:02 +00:00
|
|
|
end
|
|
|
|
end
|