Skip to content

Commit 5473eb9

Browse files
authored
encode: fix response corruption when handle_errors is used (#7235)
* encode: fix response corruption when handle_errors is used * Move disabled check before hdr assignment
1 parent 2d0f3f8 commit 5473eb9

File tree

1 file changed

+19
-1
lines changed

1 file changed

+19
-1
lines changed

modules/caddyhttp/encode/encode.go

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -177,7 +177,17 @@ func (enc *Encode) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyh
177177
break
178178
}
179179
}
180-
return next.ServeHTTP(w, r)
180+
181+
err := next.ServeHTTP(w, r)
182+
// If there was an error, disable encoding completely
183+
// This prevents corruption when handle_errors processes the response
184+
if err != nil {
185+
if ew, ok := w.(*responseWriter); ok {
186+
ew.disabled = true
187+
}
188+
}
189+
190+
return err
181191
}
182192

183193
func (enc *Encode) addEncoding(e Encoding) error {
@@ -233,6 +243,7 @@ type responseWriter struct {
233243
statusCode int
234244
wroteHeader bool
235245
isConnect bool
246+
disabled bool // disable encoding (for error responses)
236247
}
237248

238249
// WriteHeader stores the status to write when the time comes
@@ -425,7 +436,14 @@ func (rw *responseWriter) Unwrap() http.ResponseWriter {
425436

426437
// init should be called before we write a response, if rw.buf has contents.
427438
func (rw *responseWriter) init() {
439+
// Don't initialize encoder for error responses
440+
// This prevents response corruption when handle_errors is used
441+
if rw.disabled {
442+
return
443+
}
444+
428445
hdr := rw.Header()
446+
429447
if hdr.Get("Content-Encoding") == "" && isEncodeAllowed(hdr) &&
430448
rw.config.Match(rw) {
431449
rw.w = rw.config.writerPools[rw.encodingName].Get().(Encoder)

0 commit comments

Comments
 (0)