package ersteller_lib import ( "maragu.dev/gomponents" htmx "maragu.dev/gomponents-htmx" "net/http" ) type HtmxContext interface { Render(node gomponents.Node) GetLanguage() Language GetActivePath() *ActivePath HasActivePath() bool SetActivePath(activePath *ActivePath) } type HtmxContextImpl struct { req *http.Request res http.ResponseWriter language Language activePath *ActivePath } func (c *HtmxContextImpl) SetActivePath(activePath *ActivePath) { c.activePath = activePath } func (c *HtmxContextImpl) GetActivePath() *ActivePath { return c.activePath } func (c *HtmxContextImpl) HasActivePath() bool { return c.activePath != nil } func (c *HtmxContextImpl) GetLanguage() Language { return c.language } func NewHtmxContext(req *http.Request, res http.ResponseWriter, language Language) HtmxContext { return &HtmxContextImpl{req: req, res: res, language: language} } func (c *HtmxContextImpl) Render(node gomponents.Node) { err := node.Render(c.res) if err != nil { Error("failed to render", err) _, writeErr := c.res.Write([]byte(err.Error())) if writeErr != nil { Error("failed to write error", writeErr) } c.res.WriteHeader(500) } } type HtmxRouteFunc func(ctx HtmxContext) type HtmxPathParam struct { Key string Value string } type HtmxRoute interface { WithPathParams(params ...HtmxPathParam) HtmxRoute ToUrl(queryParams ...HtmxPathParam) string GetHtmx(queryParams ...HtmxPathParam) gomponents.Node SetActivePath(activePath *ActivePath) HtmxRoute } type HtmxGetRoute struct { Path string RouteFunc HtmxRouteFunc PathParams []HtmxPathParam Languages []Language ActivePath *ActivePath } func (h HtmxGetRoute) SetActivePath(activePath *ActivePath) HtmxRoute { h.ActivePath = activePath return h } func NewHtmxGetRoute(path string, routeFunc HtmxRouteFunc, languages ...Language) *HtmxGetRoute { return &HtmxGetRoute{Path: path, RouteFunc: routeFunc, Languages: languages} } func (h HtmxGetRoute) Add(server *http.ServeMux) { for _, language := range h.Languages { server.HandleFunc("GET /"+string(language)+h.Path, func(res http.ResponseWriter, req *http.Request) { context := NewHtmxContext(req, res, language) if h.ActivePath != nil { context.SetActivePath(h.ActivePath) } h.RouteFunc(context) }) } } func (h HtmxGetRoute) WithPathParams(params ...HtmxPathParam) HtmxRoute { h.PathParams = params return h } func (h HtmxGetRoute) ToUrl(queryParams ...HtmxPathParam) string { return h.Path } func (h HtmxGetRoute) GetHtmx(queryParams ...HtmxPathParam) gomponents.Node { return htmx.Get(h.ToUrl(queryParams...)) }