Add htmx route using standard lib gi
This commit is contained in:
@@ -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...))
|
||||||
|
}
|
||||||
@@ -39,3 +39,5 @@ type PageWebsiteMetaData struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type CreatePageFunc func(c echo.Context, metadata PageWebsiteMetaData, content ...Node) error
|
type CreatePageFunc func(c echo.Context, metadata PageWebsiteMetaData, content ...Node) error
|
||||||
|
|
||||||
|
type CreateHtmxPageFunc func(req HtmxContext, metadata PageWebsiteMetaData, content ...Node)
|
||||||
|
|||||||
Reference in New Issue
Block a user