From 4ebf100f099021bbec7eaa5284fe18f5f72feeb4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Steffen=20Br=C3=BCheim?= Date: Tue, 31 Aug 2021 21:36:36 +0200 Subject: encode: ignore flushing until after first write (#4318) * encode: ignore flushing until after first write (fix #4314) The first write will determine if encoding has to be done and will add an Content-Encoding. Until then Flushing has to be delayed so the Content-Encoding header can be added before headers and status code is written. (A passthrough flush would write header and status code) * Update modules/caddyhttp/encode/encode.go Co-authored-by: Matt Holt --- modules/caddyhttp/encode/encode.go | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) (limited to 'modules/caddyhttp') diff --git a/modules/caddyhttp/encode/encode.go b/modules/caddyhttp/encode/encode.go index a7abb3f..8b49205 100644 --- a/modules/caddyhttp/encode/encode.go +++ b/modules/caddyhttp/encode/encode.go @@ -182,6 +182,7 @@ type responseWriter struct { buf *bytes.Buffer config *Encode statusCode int + wroteHeader bool } // WriteHeader stores the status to write when the time comes @@ -195,6 +196,19 @@ func (enc *Encode) Match(rw *responseWriter) bool { return enc.Matcher.Match(rw.statusCode, rw.Header()) } +// Flush implements http.Flusher. It delays the actual Flush of the underlying ResponseWriterWrapper +// until headers were written. +func (rw *responseWriter) Flush() { + if !rw.wroteHeader { + // flushing the underlying ResponseWriter will write header and status code, + // but we need to delay that until we can determine if we must encode and + // therefore add the Content-Encoding header; this happens in the first call + // to rw.Write (see bug in #4314) + return + } + rw.ResponseWriterWrapper.Flush() +} + // Write writes to the response. If the response qualifies, // it is encoded using the encoder, which is initialized // if not done so already. @@ -225,6 +239,7 @@ func (rw *responseWriter) Write(p []byte) (int, error) { if rw.statusCode > 0 { rw.ResponseWriter.WriteHeader(rw.statusCode) rw.statusCode = 0 + rw.wroteHeader = true } switch { @@ -271,6 +286,7 @@ func (rw *responseWriter) Close() error { // that rely on If-None-Match, for example rw.ResponseWriter.WriteHeader(rw.statusCode) rw.statusCode = 0 + rw.wroteHeader = true } if rw.w != nil { err2 := rw.w.Close() -- cgit v1.2.3