Merge branch v2.9 into master

This commit is contained in:
Fernandez Ludovic 2022-11-23 08:51:49 +01:00 committed by kevinpollet
commit ba1ca68977
No known key found for this signature in database
GPG key ID: 0C9A5DDD1B292453
14 changed files with 261 additions and 300 deletions

View file

@ -39,11 +39,14 @@ type key string
const capturedData key = "capturedData"
// Wrap returns a new handler that inserts a Capture into the given handler.
// Wrap returns a new handler that inserts a Capture into the given handler for each incoming request.
// It satisfies the alice.Constructor type.
func Wrap(handler http.Handler) (http.Handler, error) {
c := Capture{}
return c.Reset(handler), nil
func Wrap(next http.Handler) (http.Handler, error) {
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
c := &Capture{}
newRW, newReq := c.renew(rw, req)
next.ServeHTTP(newRW, newReq)
}), nil
}
// FromContext returns the Capture value found in ctx, or an empty Capture otherwise.
@ -68,27 +71,33 @@ type Capture struct {
// NeedsReset returns whether the given http.ResponseWriter is the capture's probe.
func (c *Capture) NeedsReset(rw http.ResponseWriter) bool {
return c.crw.rw != rw
// This comparison is naive.
return c.crw != rw
}
// Reset returns a new handler that renews the Capture's probes, and inserts
// them when deferring to next.
func (c *Capture) Reset(next http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
ctx := context.WithValue(req.Context(), capturedData, c)
newReq := req.WithContext(ctx)
if newReq.Body != nil {
readCounter := &readCounter{source: newReq.Body}
c.rr = readCounter
newReq.Body = readCounter
}
c.crw = &captureResponseWriter{rw: rw}
next.ServeHTTP(c.crw, newReq)
newRW, newReq := c.renew(rw, req)
next.ServeHTTP(newRW, newReq)
})
}
func (c *Capture) renew(rw http.ResponseWriter, req *http.Request) (http.ResponseWriter, *http.Request) {
ctx := context.WithValue(req.Context(), capturedData, c)
newReq := req.WithContext(ctx)
if newReq.Body != nil {
readCounter := &readCounter{source: newReq.Body}
c.rr = readCounter
newReq.Body = readCounter
}
c.crw = &captureResponseWriter{rw: rw}
return c.crw, newReq
}
func (c *Capture) ResponseSize() int64 {
return c.crw.Size()
}