@marcel91200 / caddy Mirror · read-only / commits / 4ebf100f
Fork 0

Fast and extensible multi-platform HTTP/1-2-3 web server with automatic HTTPS

Mirrored from https://github.com/Slazee/caddy.git

Synced Nov 14, 05:15 UTC

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 <mholt@users.noreply.github.com>

Steffen Brüheim committed Aug 31, 2021 at 21:36 UTC 4ebf100f099021bbec7eaa5284fe18f5f72feeb4
1 file changed +16
modules/caddyhttp/encode/encode.go
+16
@@ -182,6 +182,7 @@ type responseWriter struct {
182 buf *bytes.Buffer
183 config *Encode
184 statusCode int
185 + wroteHeader bool
186 }
187
188 // WriteHeader stores the status to write when the time comes
@@ -195,6 +196,19 @@ func (enc *Encode) Match(rw *responseWriter) bool {
196 return enc.Matcher.Match(rw.statusCode, rw.Header())
197 }
198
199 +// Flush implements http.Flusher. It delays the actual Flush of the underlying ResponseWriterWrapper
200 +// until headers were written.
201 +func (rw *responseWriter) Flush() {
202 + if !rw.wroteHeader {
203 + // flushing the underlying ResponseWriter will write header and status code,
204 + // but we need to delay that until we can determine if we must encode and
205 + // therefore add the Content-Encoding header; this happens in the first call
206 + // to rw.Write (see bug in #4314)
207 + return
208 + }
209 + rw.ResponseWriterWrapper.Flush()
210 +}
211 +
212 // Write writes to the response. If the response qualifies,
213 // it is encoded using the encoder, which is initialized
214 // if not done so already.
@@ -225,6 +239,7 @@ func (rw *responseWriter) Write(p []byte) (int, error) {
239 if rw.statusCode > 0 {
240 rw.ResponseWriter.WriteHeader(rw.statusCode)
241 rw.statusCode = 0
242 + rw.wroteHeader = true
243 }
244
245 switch {
@@ -271,6 +286,7 @@ func (rw *responseWriter) Close() error {
286 // that rely on If-None-Match, for example
287 rw.ResponseWriter.WriteHeader(rw.statusCode)
288 rw.statusCode = 0
289 + rw.wroteHeader = true
290 }
291 if rw.w != nil {
292 err2 := rw.w.Close()