diff --git a/cmd/server/main.go b/cmd/server/main.go index b69df73..cb54344 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -44,7 +44,14 @@ func main() { "cdnjs.cloudflare.com", // highlight.js }, } - wrappedMux := middleware.CacheControlMiddleware(middleware.WithPreviewCheck(mw.WithCSP(cspConfig)(mux))) + + wrappedMux := middleware.WithURLPathValue( + middleware.CacheControlMiddleware( + middleware.WithPreviewCheck( + mw.WithCSP(cspConfig)(mux), + ), + ), + ) mux.Handle("GET /", templ.Handler(pages.Landing())) mux.Handle("GET /docs/components", http.RedirectHandler("/docs/components/accordion", http.StatusSeeOther)) @@ -105,3 +112,4 @@ func SetupAssetsRoutes(mux *http.ServeMux) { mux.Handle("GET /assets/", http.StripPrefix("/assets/", assetHandler)) } + diff --git a/internal/middleware/middleware.go b/internal/middleware/middleware.go index 0e63c81..1355440 100644 --- a/internal/middleware/middleware.go +++ b/internal/middleware/middleware.go @@ -6,6 +6,7 @@ import ( "strings" "github.com/axzilla/templui/internal/config" + "github.com/axzilla/templui/internal/utils" ) func WithPreviewCheck(next http.Handler) http.Handler { @@ -25,3 +26,17 @@ func CacheControlMiddleware(next http.Handler) http.Handler { next.ServeHTTP(w, r) }) } + +// WithURLPathValue adds the current URL's path to the context. +func WithURLPathValue(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ctx := context.WithValue( + r.Context(), + utils.CtxURLPathValueKey, + r.URL.Path, + ) + + next.ServeHTTP(w, r.WithContext(ctx)) + }) +} + diff --git a/internal/utils/utils.go b/internal/utils/utils.go index 841b8c2..8ea7a29 100644 --- a/internal/utils/utils.go +++ b/internal/utils/utils.go @@ -5,6 +5,9 @@ import ( "encoding/base64" ) +type CtxKey string + +const CtxURLPathValueKey = CtxKey("url_value") func GenerateNonce() string { nonceBytes := make([]byte, 16) _, err := rand.Read(nonceBytes)