Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Set content-length when decompressing #192

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
12 changes: 11 additions & 1 deletion lib/req/steps.ex
Original file line number Diff line number Diff line change
Expand Up @@ -861,6 +861,9 @@ defmodule Req.Steps do
| zstd | `:ezstd.decompress/1` (if [ezstd] is installed) |
| _other_ | Returns data as is |

This step updates the following headers to reflect the changes:
- `content-length` is set to the length of the decompressed body

## Options

* `:raw` - if set to `true`, disables response body decompression. Defaults to `false`.
Expand Down Expand Up @@ -902,7 +905,14 @@ defmodule Req.Steps do
{request, response}
else
compression_algorithms = get_content_encoding_header(response.headers)
{request, update_in(response.body, &decompress_body(&1, compression_algorithms))}
decompressed_body = decompress_body(response.body, compression_algorithms)
decompressed_content_length = decompressed_body |> byte_size() |> to_string()

response =
%Req.Response{response | body: decompressed_body}
|> Req.Response.put_header("content-length", decompressed_content_length)

{request, response}
end
end

Expand Down
18 changes: 18 additions & 0 deletions test/req/steps_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -370,6 +370,24 @@ defmodule Req.StepsTest do

assert Req.head!(c.url).body == ""
end

test "recalculate content-length when decompressing", c do
body = "foo"
gzipped_body = :zlib.gzip(body)

assert byte_size(body) != byte_size(gzipped_body)

Bypass.expect(c.bypass, "GET", "/", fn conn ->
conn
|> Plug.Conn.put_resp_header("content-encoding", "gzip")
|> Plug.Conn.put_resp_header("content-length", gzipped_body |> byte_size() |> to_string())
|> Plug.Conn.send_resp(200, gzipped_body)
end)

response = Req.get!(c.url)
[content_length] = Req.Response.get_header(response, "content-length")
assert String.to_integer(content_length) == byte_size(body)
end
end

describe "output" do
Expand Down