Skip to content

Commit add5e3f

Browse files
committed
Fix Content-Length for rack >= 2.1.0
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)
1 parent b5ffa70 commit add5e3f

File tree

3 files changed

+8
-5
lines changed

3 files changed

+8
-5
lines changed

lib/web_console/injector.rb

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,11 @@ def initialize(body, headers)
1313
end
1414

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

2022
[
2123
if position = @body.rindex("</body>")

test/web_console/injector_test.rb

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,11 +28,11 @@ class InjectorTest < ActiveSupport::TestCase
2828
assert_equal [ [ "foobar" ], {} ], Injector.new(body, {}).inject("bar")
2929
end
3030

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

35-
assert_equal [ [ "foobar" ], {} ], Injector.new(body, headers).inject("bar")
35+
assert_equal [ [ "foobar" ], { "Content-Length" => 6 } ], Injector.new(body, headers).inject("bar")
3636
end
3737
end
3838
end

test/web_console/middleware_test.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,7 @@ def headers
8989
@app = Middleware.new(Application.new(response_content_length: 7))
9090

9191
get "/", params: nil
92+
9293
assert_equal(response.body.size, response.headers["Content-Length"].to_i)
9394
end
9495

0 commit comments

Comments
 (0)