Skip to content

Commit

Permalink
Handle timeouts inside middlewares.
Browse files Browse the repository at this point in the history
  • Loading branch information
ernestoalejo committed Mar 24, 2024
1 parent dbbdc1c commit b56a0b5
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 10 deletions.
11 changes: 2 additions & 9 deletions handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (
"html/template"
"log/slog"
"net/http"
"time"

"github.com/altipla-consulting/env"
"github.com/altipla-consulting/errors"
Expand All @@ -19,14 +18,8 @@ func Handler(handler HandlerError) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer telemetry.ReportPanics(r.Context())

ctx := r.Context()
ctx, cancel := context.WithTimeout(ctx, 29*time.Second)
defer cancel()

r = r.WithContext(ctx)

if err := handler(w, r); err != nil {
if errors.Is(ctx.Err(), context.Canceled) {
if errors.Is(r.Context().Err(), context.Canceled) {
Error(w, http.StatusRequestTimeout)
return
}
Expand All @@ -37,7 +30,7 @@ func Handler(handler HandlerError) http.Handler {
slog.String("url", r.URL.String()))
telemetry.ReportError(r.Context(), err)

if errors.Is(ctx.Err(), context.DeadlineExceeded) {
if errors.Is(r.Context().Err(), context.DeadlineExceeded) {
Error(w, http.StatusGatewayTimeout)
return
}
Expand Down
16 changes: 15 additions & 1 deletion router.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package doris

import (
"context"
"net/http"
"time"

"libs.altipla.consulting/routing"
)
Expand All @@ -17,5 +19,17 @@ func (r *Router) PathPrefixHandlerHTTP(path string, handler http.Handler) {

// Handle sends all request to the standard HTTP handler.
func (r *Router) Handle(handler http.Handler) {
r.PathPrefixHandlerHTTP("", handler)
r.PathPrefixHandlerHTTP("", timeoutHandler(handler))
}

func timeoutHandler(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
ctx, cancel := context.WithTimeout(ctx, 29*time.Second)
defer cancel()

r = r.WithContext(ctx)

handler.ServeHTTP(w, r)
})
}

0 comments on commit b56a0b5

Please sign in to comment.