Skip to content

Commit 5bc9b82

Browse files
authored
fix: Avoid crash then gzip-decompressing empty body (#796)
When doing a HEAD-request with Accept-Encoding: gzip, some web servers set the `content-encoding` to `gzip`, but naturally transfer an empty body.
1 parent 06d4050 commit 5bc9b82

File tree

2 files changed

+13
-0
lines changed

2 files changed

+13
-0
lines changed

lib/tesla/middleware/compression.ex

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,10 @@ defmodule Tesla.Middleware.Compression do
8484
Tesla.put_header(env, "content-encoding", Enum.join(unknown_codecs, ", "))
8585
end
8686

87+
defp decompress_body(_codecs, "" = body, acc) do
88+
{body, acc}
89+
end
90+
8791
defp decompress_body([gzip | rest], body, acc) when gzip in ["gzip", "x-gzip"] do
8892
decompress_body(rest, :zlib.gunzip(body), acc)
8993
end

test/tesla/middleware/compression_test.exs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,9 @@ defmodule Tesla.Middleware.CompressionTest do
6161

6262
"/response-identity" ->
6363
{200, [{"content-type", "text/plain"}, {"content-encoding", "identity"}], "unchanged"}
64+
65+
"/response-empty" ->
66+
{200, [{"content-type", "text/plain"}, {"content-encoding", "gzip"}], ""}
6467
end
6568

6669
{:ok, %{env | status: status, headers: headers, body: body}}
@@ -84,6 +87,12 @@ defmodule Tesla.Middleware.CompressionTest do
8487
assert env.headers == [{"content-type", "text/plain"}]
8588
end
8689

90+
test "return unchanged response for empty body (gzip)" do
91+
assert {:ok, env} = CompressionResponseClient.get("/response-empty")
92+
assert env.body == ""
93+
assert env.headers == [{"content-type", "text/plain"}]
94+
end
95+
8796
defmodule CompressRequestDecompressResponseClient do
8897
use Tesla
8998

0 commit comments

Comments
 (0)