Start requiest timer in router

This commit is contained in:
DarthSim
2022-01-14 00:18:48 +06:00
parent 86b646fe1b
commit e43c24c544
3 changed files with 9 additions and 11 deletions

View File

@@ -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)

View File

@@ -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 {