Add htmx route using standard lib gi

This commit is contained in:
Achim Rohn
2025-08-11 11:41:30 +02:00
parent 177a15f022
commit 8e346a40cb
2 changed files with 76 additions and 0 deletions
+74
View File
@@ -0,0 +1,74 @@
package ersteller_lib
import (
"maragu.dev/gomponents"
htmx "maragu.dev/gomponents-htmx"
"net/http"
)
type HtmxContext interface {
Render(node gomponents.Node)
}
type HtmxContextImpl struct {
req *http.Request
res http.ResponseWriter
}
func NewHtmxContext(req *http.Request, res http.ResponseWriter) HtmxContext {
return &HtmxContextImpl{req: req, res: res}
}
func (w *HtmxContextImpl) Render(node gomponents.Node) {
err := node.Render(w.res)
if err != nil {
Error("failed to render", err)
_, writeErr := w.res.Write([]byte(err.Error()))
if writeErr != nil {
Error("failed to write error", writeErr)
}
w.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
}
type HtmxGetRoute struct {
Path string
RouteFunc HtmxRouteFunc
PathParams []HtmxPathParam
}
func NewHtmxGetRoute(path string, routeFunc HtmxRouteFunc) *HtmxGetRoute {
return &HtmxGetRoute{Path: path, RouteFunc: routeFunc}
}
func (h HtmxGetRoute) Add(server *http.ServeMux) {
server.HandleFunc("GET "+h.Path, func(res http.ResponseWriter, req *http.Request) {
h.RouteFunc(NewHtmxContext(req, res))
})
}
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...))
}