From ebd589ce9c637ac7715390baeb13e509eb49f649 Mon Sep 17 00:00:00 2001 From: WeidiDeng Date: Tue, 10 Sep 2024 22:11:37 +0800 Subject: [PATCH] rewrite request body --- modules/caddyhttp/reverseproxy/reverseproxy.go | 4 +++- modules/caddyhttp/reverseproxy/streaming.go | 3 ++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/modules/caddyhttp/reverseproxy/reverseproxy.go b/modules/caddyhttp/reverseproxy/reverseproxy.go index b8253125c..5424da4d0 100644 --- a/modules/caddyhttp/reverseproxy/reverseproxy.go +++ b/modules/caddyhttp/reverseproxy/reverseproxy.go @@ -403,8 +403,10 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyht // websocket over http2, assuming backend doesn't support this, the request will be modifided to http1.1 upgrade // TODO: once we can reliably detect backend support this, it can be removed for those backends if r.ProtoMajor == 2 && r.Method == http.MethodConnect && r.Header.Get(":protocol") != "" { - caddyhttp.SetVar(clonedReq.Context(), "h2_websocket", true) clonedReq.Header.Del(":protocol") + // keep the body for later use. http1.1 upgrade uses http.NoBody + caddyhttp.SetVar(clonedReq.Context(), "h2_websocket_body", clonedReq.Body) + clonedReq.Body = http.NoBody clonedReq.Method = http.MethodGet clonedReq.Header.Set("Upgrade", r.Header.Get(":protocol")) clonedReq.Header.Set("Connection", "Upgrade") diff --git a/modules/caddyhttp/reverseproxy/streaming.go b/modules/caddyhttp/reverseproxy/streaming.go index 71bc90942..6f2c33900 100644 --- a/modules/caddyhttp/reverseproxy/streaming.go +++ b/modules/caddyhttp/reverseproxy/streaming.go @@ -88,7 +88,8 @@ func (h *Handler) handleUpgradeResponse(logger *zap.Logger, wg *sync.WaitGroup, ) // websocket over http2, assuming backend doesn't support this, the request will be modifided to http1.1 upgrade // TODO: once we can reliably detect backend support this, it can be removed for those backends - if b, ok := caddyhttp.GetVar(req.Context(), "h2_websocket").(bool); ok && b { + if body, ok := caddyhttp.GetVar(req.Context(), "h2_websocket_body").(io.ReadCloser); ok { + req.Body = body rw.Header().Del("Upgrade") rw.Header().Del("Connection") rw.Header().Del("Sec-Websocket-Accept")