Fast and extensible multi-platform HTTP/1-2-3 web server with automatic HTTPS
Mirrored from https://github.com/Slazee/caddy.git
Synced Nov 11, 21:00 UTC
encode: fix response corruption when handle_errors is used (#7235)
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
Siomachkin committed
Sep 2, 2025 at 23:34 UTC
5473eb95d8e94505b8c06955bd200f37179c54a2
1 file changed
+19
-1
modules/caddyhttp/encode/encode.go
+19
-1
@@ -177,7 +177,17 @@ func (enc *Encode) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyh
177
break
178
}
179
}
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
191
}
192
193
func (enc *Encode) addEncoding(e Encoding) error {
@@ -233,6 +243,7 @@ type responseWriter struct {
243
statusCode int
244
wroteHeader bool
245
isConnect bool
246
+ disabled bool // disable encoding (for error responses)
247
}
248
249
// WriteHeader stores the status to write when the time comes
@@ -425,7 +436,14 @@ func (rw *responseWriter) Unwrap() http.ResponseWriter {
436
437
// init should be called before we write a response, if rw.buf has contents.
438
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
+
445
hdr := rw.Header()
446
+
447
if hdr.Get("Content-Encoding") == "" && isEncodeAllowed(hdr) &&
448
rw.config.Match(rw) {
449
rw.w = rw.config.writerPools[rw.encodingName].Get().(Encoder)