From acef3e0800290ab40a6e693d08116f78fb0de526 Mon Sep 17 00:00:00 2001 From: Ernesto Alejo Date: Sun, 23 Feb 2025 11:52:43 +0100 Subject: [PATCH] Register error middlewares for standard HTTP handlers. --- router.go | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/router.go b/router.go index 28f2ea7..92c4071 100644 --- a/router.go +++ b/router.go @@ -5,6 +5,9 @@ import ( "net/http" "time" + "github.com/altipla-consulting/errors" + "github.com/altipla-consulting/sentry" + "github.com/altipla-consulting/telemetry" "libs.altipla.consulting/routing" ) @@ -14,22 +17,33 @@ type Router struct { // PathPrefixHandlerHTTP registers a new HTTP handler for all the routes under the specified prefix. func (r *Router) PathPrefixHandlerHTTP(path string, handler http.Handler) { - r.PathPrefixHandler(path, routing.NewHandlerFromHTTP(handler)) + r.PathPrefixHandler(path, routing.NewHandlerFromHTTP(stdMiddlewares(handler))) } // Handle sends all request to the standard HTTP handler. func (r *Router) Handle(handler http.Handler) { - r.PathPrefixHandlerHTTP("", timeoutHandler(handler)) + r.PathPrefixHandlerHTTP("", stdMiddlewares(handler)) } -func timeoutHandler(handler http.Handler) http.Handler { +func stdMiddlewares(handler http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + // Timeout. ctx := r.Context() ctx, cancel := context.WithTimeout(ctx, 29*time.Second) defer cancel() - r = r.WithContext(ctx) + // Sentry body logging. + r = sentry.WithRequest(r) + + // Recover panics. + defer func() { + if rec := errors.Recover(recover()); rec != nil { + Error(w, http.StatusInternalServerError) + telemetry.ReportError(r.Context(), rec) + } + }() + handler.ServeHTTP(w, r) }) }