From 6771293336b214874a904f7d6d4bfcab35b3f165 Mon Sep 17 00:00:00 2001 From: yusing Date: Mon, 8 Dec 2025 13:45:53 +0800 Subject: [PATCH] fix(middleware): enhance response modification handling in ServeHTTP - Replaced ResponseModifier with new LazyResponseModifier. - Added logic to skip modification for non-HTML content. --- goutils | 2 +- internal/net/gphttp/middleware/middleware.go | 18 +++++++++++++++--- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/goutils b/goutils index 22ec8782..316d9a68 160000 --- a/goutils +++ b/goutils @@ -1 +1 @@ -Subproject commit 22ec87826e64f18080a31a1d58345346a012e244 +Subproject commit 316d9a68f489545718910440a737bccc6d429a33 diff --git a/internal/net/gphttp/middleware/middleware.go b/internal/net/gphttp/middleware/middleware.go index 731256e8..77fb38af 100644 --- a/internal/net/gphttp/middleware/middleware.go +++ b/internal/net/gphttp/middleware/middleware.go @@ -197,10 +197,16 @@ func (m *Middleware) ServeHTTP(next http.HandlerFunc, w http.ResponseWriter, r * } if exec, ok := m.impl.(ResponseModifier); ok { - rm := httputils.NewResponseModifier(w) - defer rm.FlushRelease() - next(rm, r) + lrm := httputils.NewLazyResponseModifier(w, needsBuffering) + defer lrm.FlushRelease() + next(lrm, r) + // Skip modification if response wasn't buffered (non-HTML content) + if !lrm.IsBuffered() { + return + } + + rm := lrm.ResponseModifier() currentBody := rm.BodyReader() currentResp := &http.Response{ StatusCode: rm.StatusCode(), @@ -228,6 +234,12 @@ func (m *Middleware) ServeHTTP(next http.HandlerFunc, w http.ResponseWriter, r * } } +// needsBuffering determines if a response should be buffered for modification. +// Only HTML responses need buffering; streaming content (video, audio, etc.) should pass through. +func needsBuffering(header http.Header) bool { + return httputils.GetContentType(header).IsHTML() +} + func (m *Middleware) LogWarn(req *http.Request) *zerolog.Event { return log.Warn().Str("middleware", m.name). Str("host", req.Host).