diff --git a/spec/std/http/client/client_spec.cr b/spec/std/http/client/client_spec.cr index 50032e3bf0af..46a4b53df210 100644 --- a/spec/std/http/client/client_spec.cr +++ b/spec/std/http/client/client_spec.cr @@ -3,13 +3,13 @@ require "openssl" require "http/client" require "http/server" -private def test_server(host, port, read_time = 0) +private def test_server(host, port, read_time = 0, content_type = "text/plain") server = TCPServer.new(host, port) begin spawn do io = server.accept sleep read_time - response = HTTP::Client::Response.new(200, headers: HTTP::Headers{"Content-Type" => "text/plain"}, body: "OK") + response = HTTP::Client::Response.new(200, headers: HTTP::Headers{"Content-Type" => content_type}, body: "OK") response.to_io(io) io.flush end @@ -213,6 +213,13 @@ module HTTP end end + it "tests empty Content-Type" do + test_server("localhost", 0, content_type: "") do |server| + client = Client.new("localhost", server.local_address.port) + client.get("/") + end + end + describe "#set_defaults" do it "sets default Host header" do client = TestClient.new "www.example.com" diff --git a/src/http/common.cr b/src/http/common.cr index 9e740d5673ce..7b61dd79dc0b 100644 --- a/src/http/common.cr +++ b/src/http/common.cr @@ -74,12 +74,16 @@ module HTTP private def self.check_content_type_charset(body, headers) return unless body - if content_type = headers["Content-Type"]? - mime_type = MIME::MediaType.parse(content_type) - if charset = mime_type["charset"]? - body.set_encoding(charset, invalid: :skip) - end - end + content_type = headers["Content-Type"]? + return unless content_type + + mime_type = MIME::MediaType.parse?(content_type) + return unless mime_type + + charset = mime_type["charset"]? + return unless charset + + body.set_encoding(charset, invalid: :skip) end # :nodoc: