Skip to content

Commit

Permalink
Register error middlewares for standard HTTP handlers.
Browse files Browse the repository at this point in the history
  • Loading branch information
ernestoalejo committed Feb 23, 2025
1 parent 1b8e241 commit acef3e0
Showing 1 changed file with 18 additions and 4 deletions.
22 changes: 18 additions & 4 deletions router.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)

Expand All @@ -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)
})
}

0 comments on commit acef3e0

Please sign in to comment.