From dea9b2f663b2a5c0909da4112aaccd6a570edd91 Mon Sep 17 00:00:00 2001 From: Micah Geisel Date: Mon, 9 Nov 2015 16:35:28 -0800 Subject: [PATCH] application/json GETs can have no request body. --- spec/param_parser_spec.cr | 35 +++++++++++++++++++++++++---------- src/kemal/param_parser.cr | 2 +- 2 files changed, 26 insertions(+), 11 deletions(-) diff --git a/spec/param_parser_spec.cr b/spec/param_parser_spec.cr index 494f90b..83ff016 100644 --- a/spec/param_parser_spec.cr +++ b/spec/param_parser_spec.cr @@ -30,18 +30,33 @@ describe "ParamParser" do params.should eq({"hasan" => "cemal", "name" => "serdar", "age" => "99"}) end - it "parses request body" do - route = Route.new "POST", "/" { } + context "when content type is application/json" do + it "parses request body" do + route = Route.new "POST", "/" { } - request = HTTP::Request.new( - "POST", - "/", - body: "{\"name\": \"Serdar\"}", - headers: HTTP::Headers{"Content-Type": "application/json"}, - ) + request = HTTP::Request.new( + "POST", + "/", + body: "{\"name\": \"Serdar\"}", + headers: HTTP::Headers{"Content-Type": "application/json"}, + ) - params = Kemal::ParamParser.new(route, request).parse - params.should eq({"name": "Serdar"}) + params = Kemal::ParamParser.new(route, request).parse + params.should eq({"name": "Serdar"}) + end + + it "handles no request body" do + route = Route.new "GET", "/" { } + + request = HTTP::Request.new( + "GET", + "/", + headers: HTTP::Headers{"Content-Type": "application/json"}, + ) + + params = Kemal::ParamParser.new(route, request).parse + params.should eq({} of String => AllParamTypes) + end end context "when content type is incorrect" do diff --git a/src/kemal/param_parser.cr b/src/kemal/param_parser.cr index 4daf81e..f8d3124 100644 --- a/src/kemal/param_parser.cr +++ b/src/kemal/param_parser.cr @@ -38,7 +38,7 @@ class Kemal::ParamParser end def parse_json - return unless @request.headers["Content-Type"]? == APPLICATION_JSON + return unless @request.body && @request.headers["Content-Type"]? == APPLICATION_JSON body = @request.body as String json = JSON.parse(body) as Hash json.each do |k, v|