From d25a611fbdd78601c53478d9a5bc11839aeb0578 Mon Sep 17 00:00:00 2001 From: Imran Latif Date: Fri, 4 Dec 2015 00:21:22 +0500 Subject: [PATCH] Implemented HTTP `HEAD` method. First I tried implementing this solution in such a way that it explicitly clears body and set `Content-Length` header to body's size. But for some reason, if I call the URL from cURL then `Content-Length` header was blank which defeats the very purpose of `HEAD` requests. I then later anticipated that since `HEAD` would be by-default implemented by `HTTP::Server` module, there is no need to explicit clears body and setting `Content-Length` but the way we have written our previous specs were returning body as well. We could have used some TestServer kind of thing but if we go to that route we explicitly need to test non-existent route which I thought would create some inconsistency among specs. Crystal has clearly written specs for HEAD requests to make sure body is not read for them. See https://github.com/manastech/crystal/commit/acd0b6afb5af438a30529c36b11b e7954336f23f. I decided to write simple specs which are easy to maintain in long-run. We are adding identical HEAD route for every GET route which will make HEAD requests available for all defined GET requests. https://github.com/sdogruyol/kemal/issues/19 Added comment for code line which is adding HEAD routes for defined GET routes. --- spec/kemal_handler_spec.cr | 17 +++++++++++++++++ src/kemal/handler.cr | 3 +++ 2 files changed, 20 insertions(+) diff --git a/spec/kemal_handler_spec.cr b/spec/kemal_handler_spec.cr index 4b0e869..3201895 100644 --- a/spec/kemal_handler_spec.cr +++ b/spec/kemal_handler_spec.cr @@ -167,4 +167,21 @@ describe "Kemal::Handler" do response.body.should eq("Hello World from DELETE") end + it "can process HTTP HEAD requests for defined GET routes" do + kemal = Kemal::Handler.new + kemal.add_route "GET", "/" do |env| + "Hello World from GET" + end + request = HTTP::Request.new("HEAD", "/") + response = kemal.call(request) + response.status_code.should eq(200) + end + + it "can't process HTTP HEAD requests for undefined GET routes" do + kemal = Kemal::Handler.new + request = HTTP::Request.new("HEAD", "/") + response = kemal.call(request) + response.status_code.should eq(404) + end + end diff --git a/src/kemal/handler.cr b/src/kemal/handler.cr index 3becf36..2d30080 100644 --- a/src/kemal/handler.cr +++ b/src/kemal/handler.cr @@ -15,6 +15,9 @@ class Kemal::Handler < HTTP::Handler 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" end def process_request(request)