From b4fb4ad0666e6758ca0c74059f3bdf7bc60527df Mon Sep 17 00:00:00 2001 From: Robin Olsen Date: Fri, 13 Feb 2026 13:39:32 +0100 Subject: [PATCH] add services and htmx middleware --- pkg/web/handler/context.go | 42 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 pkg/web/handler/context.go diff --git a/pkg/web/handler/context.go b/pkg/web/handler/context.go new file mode 100644 index 0000000..bdb1b51 --- /dev/null +++ b/pkg/web/handler/context.go @@ -0,0 +1,42 @@ +package handler + +import ( + "context" + "net/http" + + "github.com/LazyBachelor/LazyPM/internal/service" + "github.com/donseba/go-htmx" +) + +type contextKey string + +const ( + servicesKey contextKey = "services" + htmxKey contextKey = "htmx" +) + +func ServicesMiddleware(svc *service.Services) func(http.Handler) http.Handler { + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ctx := context.WithValue(r.Context(), servicesKey, svc) + next.ServeHTTP(w, r.WithContext(ctx)) + }) + } +} + +func HTMXMiddleware(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + htmxInstance := htmx.New() + handler := htmxInstance.NewHandler(w, r) + ctx := context.WithValue(r.Context(), htmxKey, handler) + next.ServeHTTP(w, r.WithContext(ctx)) + }) +} + +func Services(r *http.Request) *service.Services { + return r.Context().Value(servicesKey).(*service.Services) +} + +func HTMX(r *http.Request) *htmx.Handler { + return r.Context().Value(htmxKey).(*htmx.Handler) +}