Skip to content

Commit

Permalink
fix: incorrect mime type parsing
Browse files Browse the repository at this point in the history
  • Loading branch information
kimburgess committed Oct 14, 2020
1 parent 0ee414c commit 985d7b4
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 4 deletions.
12 changes: 12 additions & 0 deletions spec/responsible/response_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,18 @@ describe Responsible::Response do
end
error_block_executed.should be_true
end

it "correctly parses content types" do
WebMock.stub(:get, "www.example.com").to_return(
headers: { "Content-Type" => "application/json; charset=UTF-8" },
body: <<-JSON
{"value":"foo"}
JSON
)
response = ~HTTP::Client.get("www.example.com")
result = response.parse_to NamedTuple(value: String)
result[:value].should eq("foo")
end
end

describe "#parse_to?" do
Expand Down
8 changes: 4 additions & 4 deletions src/responsible/response.cr
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
require "json"
require "mime/media_type"
require "./response_interface"
require "./response_type"

Expand Down Expand Up @@ -55,17 +56,16 @@ class Responsible::Response
def parse_to(x : T.class, ignore_response_code = @in_handler, &block : Exception -> U) : T | U forall T, U
raise Error.from(self) unless success? || ignore_response_code

content_type = headers["content-type"].split(' ').first.downcase
mime_type = MIME::MediaType.parse headers["Content-Type"]

case content_type
when "application/json"
if mime_type.media_type == "application/json"
begin
T.from_json(@response.body? || @response.body_io)
rescue e
yield e
end
else
raise Error.new "unsupported content type (#{content_type})"
raise Error.new "unsupported MIME type (#{mime_type})"
end
end

Expand Down

0 comments on commit 985d7b4

Please sign in to comment.