refactor(middleware): improve response body modification gating

Refactor response body modification to only allow text-like content types
(JSON, YAML, XML, etc.) instead of all HTML responses.

Body modification is now
blocked for binary content and transfer/content encoded responses, while status
code and headers can still be modified.

This prevents issues with compressed or streaming responses while
maintaining the ability to modify text-based API responses.
This commit is contained in:
yusing
2026-02-23 23:46:41 +08:00
parent 0850ea3918
commit 169358659a
6 changed files with 206 additions and 22 deletions

View File

@@ -1,6 +1,7 @@
package middleware
import (
"maps"
"net/http"
"strconv"
@@ -46,10 +47,23 @@ func (m *middlewareChain) modifyResponse(resp *http.Response) error {
if len(m.modResps) == 0 {
return nil
}
allowBodyModification := canModifyResponseBody(resp)
for i, mr := range m.modResps {
if err := mr.modifyResponse(resp); err != nil {
respToModify := resp
if !allowBodyModification {
shadow := *resp
shadow.Body = eofReader{}
respToModify = &shadow
}
if err := mr.modifyResponse(respToModify); err != nil {
return gperr.PrependSubject(err, strconv.Itoa(i))
}
if !allowBodyModification {
resp.StatusCode = respToModify.StatusCode
if respToModify.Header != nil {
maps.Copy(resp.Header, respToModify.Header)
}
}
}
return nil
}