1
0
mirror of https://github.com/axzilla/templui.git synced 2025-02-21 01:32:45 +00:00

feat(server): add middleware to populate context with url path

This commit is contained in:
Arthur Wallendorff 2025-02-08 13:52:30 +01:00
parent c5d2aa3c95
commit eeba21442c
3 changed files with 27 additions and 1 deletions

View File

@ -44,7 +44,14 @@ func main() {
"cdnjs.cloudflare.com", // highlight.js "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 /", templ.Handler(pages.Landing()))
mux.Handle("GET /docs/components", http.RedirectHandler("/docs/components/accordion", http.StatusSeeOther)) 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)) mux.Handle("GET /assets/", http.StripPrefix("/assets/", assetHandler))
} }

View File

@ -6,6 +6,7 @@ import (
"strings" "strings"
"github.com/axzilla/templui/internal/config" "github.com/axzilla/templui/internal/config"
"github.com/axzilla/templui/internal/utils"
) )
func WithPreviewCheck(next http.Handler) http.Handler { func WithPreviewCheck(next http.Handler) http.Handler {
@ -25,3 +26,17 @@ func CacheControlMiddleware(next http.Handler) http.Handler {
next.ServeHTTP(w, r) 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))
})
}

View File

@ -5,6 +5,9 @@ import (
"encoding/base64" "encoding/base64"
) )
type CtxKey string
const CtxURLPathValueKey = CtxKey("url_value")
func GenerateNonce() string { func GenerateNonce() string {
nonceBytes := make([]byte, 16) nonceBytes := make([]byte, 16)
_, err := rand.Read(nonceBytes) _, err := rand.Read(nonceBytes)