From 00b63ec5a5497aa2fa9777a3e899134718a13fd6 Mon Sep 17 00:00:00 2001 From: Jordan Moncharmont Date: Wed, 23 May 2012 13:39:31 -0700 Subject: [PATCH] HEAD requests on static files should have proper Content-Length Code originally intending to fix byte encodings was overwriting the proper Content-Length headers set by send_file also contains 2 trailing whitespace fixes --- lib/sinatra/base.rb | 8 +++++--- test/static_test.rb | 1 + 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/lib/sinatra/base.rb b/lib/sinatra/base.rb index 29384f2d74..7f5081a21d 100644 --- a/lib/sinatra/base.rb +++ b/lib/sinatra/base.rb @@ -77,7 +77,9 @@ def finish headers.delete "Content-Length" headers.delete "Content-Type" elsif Array === body and not [204, 304].include?(status.to_i) - headers["Content-Length"] = body.inject(0) { |l, p| l + Rack::Utils.bytesize(p) }.to_s + # if some other code has already set Content-Length, don't muck with it + # currently, this would be the static file-handler + headers["Content-Length"] ||= body.inject(0) { |l, p| l + Rack::Utils.bytesize(p) }.to_s end # Rack::Response#finish sometimes returns self as response body. We don't want that. @@ -986,7 +988,7 @@ def handle_exception!(boom) def error_block!(key, *block_params) base = settings while base.respond_to?(:errors) - next base = base.superclass unless args_array = base.errors[key] + next base = base.superclass unless args_array = base.errors[key] args_array.reverse_each do |args| first = args == args_array.first args += [block_params] @@ -1092,7 +1094,7 @@ def disable(*opts) # Define a custom error handler. Optionally takes either an Exception # class, or an HTTP status code to specify which errors should be # handled. - def error(*codes, &block) + def error(*codes, &block) args = compile! "ERROR", //, block codes = codes.map { |c| Array(c) }.flatten codes << Exception if codes.empty? diff --git a/test/static_test.rb b/test/static_test.rb index 320b70bb95..04a740c3b7 100644 --- a/test/static_test.rb +++ b/test/static_test.rb @@ -37,6 +37,7 @@ class StaticTest < Test::Unit::TestCase assert ok? assert_equal '', body assert response.headers.include?('Last-Modified') + assert_equal File.size(__FILE__).to_s, response['Content-Length'] end %w[POST PUT DELETE].each do |verb|