From 28859fbdb801e488b3a4b4834f7cdba25df72273 Mon Sep 17 00:00:00 2001 From: Sijawusz Pur Rahnama Date: Thu, 11 Aug 2016 21:29:29 +0200 Subject: [PATCH] Fix parsing JSON params when "charset" is present in "Content-Type" header (#193) Resolves case when `Content-Type` headers is passed in form of `application/json; charset=utf-8` --- spec/param_parser_spec.cr | 14 ++++++++++++++ src/kemal/param_parser.cr | 2 +- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/spec/param_parser_spec.cr b/spec/param_parser_spec.cr index a13d373..a154bd4 100644 --- a/spec/param_parser_spec.cr +++ b/spec/param_parser_spec.cr @@ -91,6 +91,20 @@ describe "ParamParser" do json_params.should eq({"name" => "Serdar"}) end + it "parses request body when passed charset" do + route = Route.new "POST", "/" { } + + request = HTTP::Request.new( + "POST", + "/", + body: "{\"name\": \"Serdar\"}", + headers: HTTP::Headers{"Content-Type" => "application/json; charset=utf-8"}, + ) + + json_params = Kemal::ParamParser.new(request).json + json_params.should eq({"name" => "Serdar"}) + end + it "parses request body for array" do route = Route.new "POST", "/" { } diff --git a/src/kemal/param_parser.cr b/src/kemal/param_parser.cr index 5ea291e..d1e5464 100644 --- a/src/kemal/param_parser.cr +++ b/src/kemal/param_parser.cr @@ -55,7 +55,7 @@ module Kemal # If request body is a JSON Array it's added into `params` as `_json` and can be accessed # like params["_json"] def parse_json - return unless @request.body && @request.headers["Content-Type"]? == APPLICATION_JSON + return unless @request.body && @request.headers["Content-Type"]?.try(&.[APPLICATION_JSON]?) body = @request.body.as(String) case json = JSON.parse(body).raw