diff --git a/processing_handler.go b/processing_handler.go index b0db77ac..a9a18b2e 100644 --- a/processing_handler.go +++ b/processing_handler.go @@ -1,7 +1,6 @@ package main import ( - "context" "fmt" "net/http" "net/http/cookiejar" @@ -138,11 +137,7 @@ func respondWithNotModified(reqID string, r *http.Request, rw http.ResponseWrite } func handleProcessing(reqID string, rw http.ResponseWriter, r *http.Request) { - ctx, timeoutCancel := context.WithTimeout(r.Context(), time.Duration(config.WriteTimeout)*time.Second) - defer timeoutCancel() - - var metricsCancel context.CancelFunc - ctx, metricsCancel, rw = metrics.StartRequest(ctx, rw, r) + ctx, metricsCancel, rw := metrics.StartRequest(r.Context(), rw, r) defer metricsCancel() path := r.RequestURI diff --git a/router/router.go b/router/router.go index 6f285c61..d5874dfd 100644 --- a/router/router.go +++ b/router/router.go @@ -71,7 +71,8 @@ func (r *Router) HEAD(prefix string, handler RouteHandler, exact bool) { } func (r *Router) ServeHTTP(rw http.ResponseWriter, req *http.Request) { - req = setRequestTime(req) + req, timeoutCancel := startRequestTimer(req) + defer timeoutCancel() reqID := req.Header.Get(xRequestIDHeader) diff --git a/router/timer.go b/router/timer.go index efce6dbb..b34a6f00 100644 --- a/router/timer.go +++ b/router/timer.go @@ -6,16 +6,18 @@ import ( "net/http" "time" + "github.com/imgproxy/imgproxy/v3/config" "github.com/imgproxy/imgproxy/v3/ierrors" "github.com/imgproxy/imgproxy/v3/metrics" ) type timerSinceCtxKey = struct{} -func setRequestTime(r *http.Request) *http.Request { - return r.WithContext( - context.WithValue(r.Context(), timerSinceCtxKey{}, time.Now()), - ) +func startRequestTimer(r *http.Request) (*http.Request, context.CancelFunc) { + ctx := r.Context() + ctx = context.WithValue(ctx, timerSinceCtxKey{}, time.Now()) + ctx, cancel := context.WithTimeout(ctx, time.Duration(config.WriteTimeout)*time.Second) + return r.WithContext(ctx), cancel } func ctxTime(ctx context.Context) time.Duration {