From 9919e7445191f49645ea958270b4cf0d36c737b2 Mon Sep 17 00:00:00 2001 From: Eero Saynatkari Date: Fri, 9 Jan 2009 18:28:09 +0200 Subject: [PATCH] Update Content-Length in Response#write, not in #finish. Spec. * This means that the absence of the Content-Length header can actually be used by the ContentLength middleware to figure out if it should run. * There is no "default" Content-Length. --- lib/rack/response.rb | 7 ++++++- test/spec_rack_response.rb | 27 +++++++++++++++++++++++++-- 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/lib/rack/response.rb b/lib/rack/response.rb index 97deb6e..1d6875d 100644 --- a/lib/rack/response.rb +++ b/lib/rack/response.rb @@ -100,7 +100,6 @@ module Rack header.delete "Content-Type" [status.to_i, header.to_hash, []] else - header["Content-Length"] ||= @length.to_s [status.to_i, header.to_hash, self] end end @@ -112,10 +111,16 @@ module Rack @block.call(self) if @block end + # Append to body and update Content-Length. + # + # NOTE: Do not mix #write and direct #body access! + # def write(str) s = str.to_s @length += s.size @writer.call s + + header["Content-Length"] = @length.to_s str end diff --git a/test/spec_rack_response.rb b/test/spec_rack_response.rb index 748007a..5699fbe 100644 --- a/test/spec_rack_response.rb +++ b/test/spec_rack_response.rb @@ -8,7 +8,7 @@ context "Rack::Response" do response = Rack::Response.new status, header, body = response.finish status.should.equal 200 - header.should.equal "Content-Type" => "text/html", "Content-Length" => "0" + header.should.equal "Content-Type" => "text/html" body.each { |part| part.should.equal "" } @@ -16,7 +16,7 @@ context "Rack::Response" do response = Rack::Response.new status, header, body = *response status.should.equal 200 - header.should.equal "Content-Type" => "text/html", "Content-Length" => "0" + header.should.equal "Content-Type" => "text/html" body.each { |part| part.should.equal "" } @@ -171,4 +171,27 @@ context "Rack::Response" do res.location.should.be.nil end + specify "does not add or change Content-Length when #finish()ing" do + res = Rack::Response.new + res.status = 200 + res.finish + res.headers["Content-Length"].should.be.nil + + res = Rack::Response.new + res.status = 200 + res.headers["Content-Length"] = "10" + res.finish + res.headers["Content-Length"].should.equal "10" + end + + specify "updates Content-Length when body appended to using #write" do + res = Rack::Response.new + res.status = 200 + res.headers["Content-Length"].should.be.nil + res.write "Hi" + res.headers["Content-Length"].should.equal "2" + res.write " there" + res.headers["Content-Length"].should.equal "8" + end + end -- 1.6.0.2