Browse Source

Start requiest timer in router

DarthSim 3 years ago
parent
commit
e43c24c544
3 changed files with 9 additions and 11 deletions
  1. 1 6
      processing_handler.go
  2. 2 1
      router/router.go
  3. 6 4
      router/timer.go

+ 1 - 6
processing_handler.go

@@ -1,7 +1,6 @@
 package main
 package main
 
 
 import (
 import (
-	"context"
 	"fmt"
 	"fmt"
 	"net/http"
 	"net/http"
 	"net/http/cookiejar"
 	"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) {
 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()
 	defer metricsCancel()
 
 
 	path := r.RequestURI
 	path := r.RequestURI

+ 2 - 1
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) {
 func (r *Router) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
-	req = setRequestTime(req)
+	req, timeoutCancel := startRequestTimer(req)
+	defer timeoutCancel()
 
 
 	reqID := req.Header.Get(xRequestIDHeader)
 	reqID := req.Header.Get(xRequestIDHeader)
 
 

+ 6 - 4
router/timer.go

@@ -6,16 +6,18 @@ import (
 	"net/http"
 	"net/http"
 	"time"
 	"time"
 
 
+	"github.com/imgproxy/imgproxy/v3/config"
 	"github.com/imgproxy/imgproxy/v3/ierrors"
 	"github.com/imgproxy/imgproxy/v3/ierrors"
 	"github.com/imgproxy/imgproxy/v3/metrics"
 	"github.com/imgproxy/imgproxy/v3/metrics"
 )
 )
 
 
 type timerSinceCtxKey = struct{}
 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 {
 func ctxTime(ctx context.Context) time.Duration {