diff --git a/internal/rproxy/bodies.go b/internal/rproxy/bodies.go index 4a52bc1..6563624 100644 --- a/internal/rproxy/bodies.go +++ b/internal/rproxy/bodies.go @@ -2,6 +2,7 @@ package rproxy import ( "bufio" + "context" "errors" "io" "net" @@ -22,7 +23,9 @@ type requestBody struct { // body is the visitor's body, ending in an *http.MaxBytesError past // SWW_RPROXY_MAX_REQUEST_SIZE. body io.ReadCloser - rq *request + // refuse refuses the request with a status, as the request's own refuse + // does. + refuse func(status int) // held is the part read before the request goes to the app, which Read gives // first. held []byte @@ -68,7 +71,7 @@ func (b *requestBody) Read(p []byte) (int, error) { case errors.Is(err, io.EOF): b.received.Store(true) case errors.As(err, &tooLarge): - b.rq.refuse(http.StatusRequestEntityTooLarge) + b.refuse(http.StatusRequestEntityTooLarge) } return n, err @@ -86,7 +89,13 @@ type responseBody struct { // body is the app's body, ending in an *http.MaxBytesError past // SWW_RPROXY_MAX_RESPONSE_SIZE. body io.ReadCloser - rq *request + // refuse refuses the request with a status, as the request's own refuse + // does. + refuse func(status int) + // responseReceived is called once the app's whole answer has arrived. + responseReceived func() + // ctx is the visitor's request's context. + ctx context.Context //nolint:containedctx // the body ends with the request } // Read reads from the app's body. @@ -100,15 +109,15 @@ func (b *responseBody) Read(p []byte) (int, error) { switch { case errors.Is(err, io.EOF): - b.rq.responseReceived() + b.responseReceived() case errors.As(err, &tooLarge): - b.rq.refuse(http.StatusBadGateway) + b.refuse(http.StatusBadGateway) return n, errResponseTooLarge - case b.rq.in.Context().Err() == nil: + case b.ctx.Err() == nil: // The answer broke off, not because the visitor went away. If a time // limit cut it, that refusal came first and is the one kept. - b.rq.refuse(http.StatusBadGateway) + b.refuse(http.StatusBadGateway) } return n, err diff --git a/internal/rproxy/request.go b/internal/rproxy/request.go index 2246bd7..cd4aeae 100644 --- a/internal/rproxy/request.go +++ b/internal/rproxy/request.go @@ -126,8 +126,8 @@ func (h *handler) newRequest( if r.Body != http.NoBody { rq.body = &requestBody{ - body: limitBody(r.Body, h.config.MaxRequestSize), - rq: rq, + body: limitBody(r.Body, h.config.MaxRequestSize), + refuse: rq.refuse, } } @@ -294,7 +294,12 @@ func (rq *request) modifyResponse(res *http.Response) error { // the request, and SWW_RPROXY_MAX_RESPONSE_TIME_MS starts. rq.startResponseTimer(requestEnd) - res.Body = &responseBody{body: limitBody(res.Body, maxBytes), rq: rq} + res.Body = &responseBody{ + body: limitBody(res.Body, maxBytes), + refuse: rq.refuse, + responseReceived: rq.responseReceived, + ctx: rq.in.Context(), + } rq.out.afterStatus = rq.setResponseDeadline return nil