Files
LazyPM/pkg/web/handler/context.go
Robin Olsen aabce0b0b2 refactor to use app package instead of service
refactor app to be composable
2026-02-28 23:30:31 +01:00

43 lines
999 B
Go

package handler
import (
"context"
"net/http"
"github.com/LazyBachelor/LazyPM/internal/app"
"github.com/donseba/go-htmx"
)
type contextKey string
const (
appKey contextKey = "app"
htmxKey contextKey = "htmx"
)
func AppMiddleware(app *app.App) 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(), appKey, app)
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 App(r *http.Request) *app.App {
return r.Context().Value(appKey).(*app.App)
}
func HTMX(r *http.Request) *htmx.Handler {
return r.Context().Value(htmxKey).(*htmx.Handler)
}