Skip to content

Commit 8d1a3d6

Browse files
committed
fix: Drop a handler's Content-Length when a stream is compressed
A compressed stream goes out chunked, and the JDK's chunked branch sets Transfer-encoding without clearing a Content-Length the handler put on the response — so both framing headers reached the wire together. Before this branch a sized stream passed its real length, which made the JDK overwrite that header, so the conflict is new. The declared length also describes the uncompressed body, so it is wrong on the wire regardless of framing. renderEmpty already removed it for the same reason; renderStream now does too.
1 parent e25665c commit 8d1a3d6

2 files changed

Lines changed: 17 additions & 0 deletions

File tree

src/main/java/com/retailsvc/http/internal/ResponseRenderer.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,8 @@ private void renderStream(
8282
boolean gzip = shouldCompress(exchange, headers, status, contentType, declared);
8383
if (gzip) {
8484
headers.set(CONTENT_ENCODING, GZIP);
85+
// The coded body goes out chunked, and the JDK leaves a handler-set length in place there.
86+
headers.remove(CONTENT_LENGTH);
8587
}
8688
exchange.sendResponseHeaders(status, gzip ? CHUNKED : Math.max(declared, CHUNKED));
8789
try (OutputStream out =

src/test/java/com/retailsvc/http/internal/ResponseRendererTest.java

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -397,6 +397,21 @@ void skipsCompressionOnStreamWhenHandlerAlreadySetContentEncoding() throws IOExc
397397
assertThat(sink.toByteArray()).isEqualTo(payload);
398398
}
399399

400+
@Test
401+
void stripsHandlerContentLengthWhenStreamIsCompressed() throws IOException {
402+
acceptsGzip();
403+
byte[] payload = largeText();
404+
405+
renderer.render(
406+
exchange,
407+
Response.stream(HTTP_OK, payload.length, TEXT, out -> out.write(payload))
408+
.withHeader("Content-Length", String.valueOf(payload.length)));
409+
410+
assertThat(responseHeaders.getFirst(CONTENT_ENCODING)).isEqualTo("gzip");
411+
assertThat(responseHeaders.getFirst("Content-Length")).isNull();
412+
assertThat(length.get()).isZero();
413+
}
414+
400415
private void acceptsGzip() {
401416
requestHeaders.add("Accept-Encoding", "gzip, deflate, br");
402417
}

0 commit comments

Comments
 (0)