From 39e9932285b9d1f6c4517849fb9357813d4c38e1 Mon Sep 17 00:00:00 2001 From: Jip van Reijsen Date: Wed, 20 Jul 2016 16:40:11 +0200 Subject: [PATCH] Set Content-Length request header when request body is nil When the body is a String, the Content-Length header was already set. --- lib/http/request/writer.rb | 2 ++ spec/lib/http/request/writer_spec.rb | 18 ++++++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/lib/http/request/writer.rb b/lib/http/request/writer.rb index c9b2404e..36de075d 100644 --- a/lib/http/request/writer.rb +++ b/lib/http/request/writer.rb @@ -53,6 +53,8 @@ def connect_through_proxy def add_body_type_headers if @body.is_a?(String) && !@headers[Headers::CONTENT_LENGTH] @request_header << "#{Headers::CONTENT_LENGTH}: #{@body.bytesize}" + elsif @body.nil? && !@headers[Headers::CONTENT_LENGTH] + @request_header << "#{Headers::CONTENT_LENGTH}: 0" elsif @body.is_a?(Enumerable) && CHUNKED != @headers[Headers::TRANSFER_ENCODING] raise(RequestError, "invalid transfer encoding") end diff --git a/spec/lib/http/request/writer_spec.rb b/spec/lib/http/request/writer_spec.rb index ac7ed1f8..a5d27c56 100644 --- a/spec/lib/http/request/writer_spec.rb +++ b/spec/lib/http/request/writer_spec.rb @@ -69,6 +69,24 @@ end end + context "when body is nil" do + let(:body) { nil } + + it "properly sets Content-Length header if needed" do + writer.stream + expect(io.string).to start_with "#{headerstart}\r\nContent-Length: 0\r\n\r\n" + end + + context "when Content-Length explicitly set" do + let(:headers) { HTTP::Headers.coerce "Content-Length" => 12 } + + it "keeps given value" do + writer.stream + expect(io.string).to start_with "#{headerstart}\r\nContent-Length: 12\r\n\r\n" + end + end + end + context "when body is a unicode String" do let(:body) { "Привет, мир!" }