From a9ed5484731d245de69e388a40c44dc028f1e0dd Mon Sep 17 00:00:00 2001 From: Achim Rohn Date: Wed, 13 Aug 2025 14:59:28 +0200 Subject: [PATCH] Implement out week change via date input --- htmx_route.go | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/htmx_route.go b/htmx_route.go index d9a50d2..5d8bc3d 100644 --- a/htmx_route.go +++ b/htmx_route.go @@ -1,6 +1,8 @@ package ersteller_lib import ( + "encoding/json" + "fmt" "maragu.dev/gomponents" htmx "maragu.dev/gomponents-htmx" "net/http" @@ -16,6 +18,8 @@ type HtmxContext interface { SetActivePath(activePath *ActivePath) GetPath() string GetPathParam(key string, defaultValue ...string) string + GetFormValue(key string) string + SetHeader(key string, value string) } type HtmxContextImpl struct { @@ -25,6 +29,20 @@ type HtmxContextImpl struct { activePath *ActivePath } +func (c *HtmxContextImpl) SetHeader(key string, value string) { + c.res.Header().Set(key, value) +} + +func (c *HtmxContextImpl) GetFormValue(key string) string { + err := c.req.ParseForm() + if err != nil { + Error("failed to parse form", err) + c.SetError(err) + return "" + } + return c.req.FormValue(key) +} + func (c *HtmxContextImpl) SetError(err error) { _, writeErr := c.res.Write([]byte(err.Error())) if writeErr != nil { @@ -83,6 +101,12 @@ type HtmxPathParam struct { Value string } +type LocationRedirectParams struct { + Path string `json:"path"` + Target string `json:"target,omitempty"` + Swap string `json:"swap,omitempty"` +} + type HtmxRoute interface { WithPathParams(params ...HtmxPathParam) HtmxRoute ToUrl(language Language, queryParams ...HtmxPathParam) string @@ -90,6 +114,7 @@ type HtmxRoute interface { SetActivePath(activePath *ActivePath) HtmxRoute Add(server *http.ServeMux) Execute(c HtmxContext) + RedirectToThisRoute(c HtmxContext, params LocationRedirectParams) } func addLanguageToPath(path string, language Language) string { @@ -105,6 +130,18 @@ type CommonHtmxRoute struct { HtmxMethod HtmxHttpMethodFunction } +func (h CommonHtmxRoute) RedirectToThisRoute(c HtmxContext, params LocationRedirectParams) { + params.Path = h.ToUrl(c.GetLanguage()) + jsonData, err := json.Marshal(params) + if err != nil { + marshalError := fmt.Errorf("failed to marshal LocationRedirectParams: %w, %w", err, params) + Error(marshalError) + c.SetError(marshalError) + return + } + c.SetHeader("HX-Location", string(jsonData)) +} + func NewCommonHtmxRoute(routeFunc HtmxRouteFunc, paths LanguagePaths, method string, htmxMethod HtmxHttpMethodFunction) *CommonHtmxRoute { return &CommonHtmxRoute{RouteFunc: routeFunc, Paths: paths, Method: method, HtmxMethod: htmxMethod}