Skip to content

Commit

Permalink
Fix Content-Length for rack >= 2.1.0
Browse files Browse the repository at this point in the history
Since rack 2.1.0 the Content-Length header is no longer updated for
if the body argument isn't a string. This was done for performance
reasons. It is recommended to set Content-Length header in the
middlewate instead.

rack/rack#1472 (comment)
  • Loading branch information
p8 committed May 28, 2020
1 parent b5ffa70 commit bcd7776
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 5 deletions.
8 changes: 5 additions & 3 deletions lib/web_console/injector.rb
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,11 @@ def initialize(body, headers)
end

def inject(content)
# Remove any previously set Content-Length header because we modify
# the body. Otherwise the response will be truncated.
@headers.delete("Content-Length")
# Set Content-Length header to the size of the current body
# + the extra content. Otherwise the response will be truncated.
if @headers["Content-Length"]
@headers["Content-Length"] = @body.bytesize + content.bytesize
end

[
if position = @body.rindex("</body>")
Expand Down
4 changes: 2 additions & 2 deletions test/web_console/injector_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,11 @@ class InjectorTest < ActiveSupport::TestCase
assert_equal [ [ "foobar" ], {} ], Injector.new(body, {}).inject("bar")
end

test "deletes the Content-Length header" do
test "updates the Content-Length header" do
body = [ "foo" ]
headers = { "Content-Length" => 3 }

assert_equal [ [ "foobar" ], {} ], Injector.new(body, headers).inject("bar")
assert_equal [ [ "foobar" ], { "Content-Length" => 6 } ], Injector.new(body, headers).inject("bar")
end
end
end
1 change: 1 addition & 0 deletions test/web_console/middleware_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ def headers
@app = Middleware.new(Application.new(response_content_length: 7))

get "/", params: nil

assert_equal(response.body.size, response.headers["Content-Length"].to_i)
end

Expand Down

0 comments on commit bcd7776

Please sign in to comment.