Skip to content

Commit

Permalink
feat(middlewares): update timeout middleware to set the processing ti…
Browse files Browse the repository at this point in the history
…meout based on some conditions like path and method
  • Loading branch information
jeamon committed Nov 13, 2023
1 parent 30bb544 commit 29d1134
Showing 1 changed file with 16 additions and 3 deletions.
19 changes: 16 additions & 3 deletions api.middlewares.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"fmt"
"net/http"
"sync/atomic"
"time"

"github.com/julienschmidt/httprouter"
"go.uber.org/zap"
Expand All @@ -31,8 +32,9 @@ type MiddlewareMap struct {
func (api *APIHandler) StatsMiddleware(next httprouter.Handle) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
logger := api.GetLoggerFromContext(r.Context())
conn := GetConnFromContext(r.Context())
nw := NewCustomResponseWriter(w, conn)
start := api.clock.Now()
nw := NewCustomResponseWriter(w)
next(nw, r, ps)
logger.Info(
"stats",
Expand Down Expand Up @@ -144,8 +146,8 @@ func (api *APIHandler) TimeoutMiddleware(next httprouter.Handle) httprouter.Hand
return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
requestID := GetValueFromContext(r.Context(), ContextRequestID)
logger := api.GetLoggerFromContext(r.Context())
timeout := api.config.Server.RequestTimeout
ctx, cancel := context.WithTimeout(r.Context(), api.config.Server.RequestTimeout)
timeout := api.GetTimeout(r)
ctx, cancel := context.WithTimeout(r.Context(), timeout)
defer cancel()
r = r.WithContext(ctx)
done := make(chan struct{})
Expand Down Expand Up @@ -176,6 +178,17 @@ func (api *APIHandler) TimeoutMiddleware(next httprouter.Handle) httprouter.Hand
}
}

// GetTimeout returns the processing timeout to use to update
// a given request context deadline based on path and method.
func (api *APIHandler) GetTimeout(r *http.Request) time.Duration {
switch {
case r.Method == "GET" && r.URL.Path == "/v1/books":
return api.config.Server.LongRequestProcessingTimeout
default:
return api.config.Server.RequestTimeout
}
}

// Chain wraps a given httprouter.Handle with a list of middlewares.
// It does by starting from the last middleware from the list.
func (m *Middlewares) Chain(h httprouter.Handle) httprouter.Handle {
Expand Down

0 comments on commit 29d1134

Please sign in to comment.