diff --git a/smalltrip/problem/middleware.go b/smalltrip/problem/middleware.go new file mode 100644 index 0000000..c51993c --- /dev/null +++ b/smalltrip/problem/middleware.go @@ -0,0 +1,32 @@ +package problem + +import ( + "context" + "net/http" + + "forge.capytal.company/loreddev/x/smalltrip/middleware" +) + +func Middleware(h Handler) middleware.Middleware { + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ctx := context.WithValue(r.Context(), contextKey, h) + next.ServeHTTP(w, r.WithContext(ctx)) + }) + } +} + +func HandlerMiddleware(fallback ...Handler) Handler { + return func(p Problem) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + handler := r.Context().Value(contextKey) + if h, ok := handler.(Handler); handler != nil && ok { + h(p).ServeHTTP(w, r) + } else if len(fallback) > 0 { + fallback[0](p).ServeHTTP(w, r) + } + }) + } +} + +var contextKey = "x-smalltrip-problems-middleware-handler"