From ff5c4711b07998ba1124e85318379643383b4d19 Mon Sep 17 00:00:00 2001 From: Achim Rohn Date: Wed, 13 Aug 2025 11:42:36 +0200 Subject: [PATCH] Render a default route and static files from a function in lib --- htmx_route.go | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/htmx_route.go b/htmx_route.go index c06e25e..ffa4e33 100644 --- a/htmx_route.go +++ b/htmx_route.go @@ -147,3 +147,20 @@ func (h HtmxGetRoute) ToUrl(language Language, queryParams ...HtmxPathParam) str func (h HtmxGetRoute) GetHtmx(language Language, queryParams ...HtmxPathParam) gomponents.Node { return htmx.Get(h.ToUrl(language, queryParams...)) } + +func HandleStaticAndDefaultPath(server *http.ServeMux, defaultRoute HtmxRoute, defaultLanguage Language) func(http.ResponseWriter, *http.Request) { + staticHandler := http.StripPrefix("/static", http.FileServer(http.Dir("./static"))) + server.Handle("GET /static", staticHandler) + return func(w http.ResponseWriter, r *http.Request) { + path := r.URL.Path + if strings.HasPrefix(path, "/static") { + staticHandler.ServeHTTP(w, r) + return + } + if path == "/" { + defaultRoute.Execute(NewHtmxContext(r, w, defaultLanguage)) + return + } + http.Error(w, "Not found", http.StatusNotFound) + } +}