summaryrefslogtreecommitdiff
path: root/pages/page.go
diff options
context:
space:
mode:
Diffstat (limited to 'pages/page.go')
-rw-r--r--pages/page.go58
1 files changed, 36 insertions, 22 deletions
diff --git a/pages/page.go b/pages/page.go
index 25c2331..6ce8cee 100644
--- a/pages/page.go
+++ b/pages/page.go
@@ -3,10 +3,10 @@ package pages
import (
"context"
"gosten/model"
- "gosten/templ"
"log"
"net/http"
+ "github.com/a-h/templ"
"github.com/go-chi/chi/v5"
)
@@ -20,39 +20,53 @@ type Page interface {
http.Handler
}
-type dataFunc func(r *http.Request, uid int32) any
+type dataFunc[T any] func(r *http.Request, uid int32) T
+type tplFunc[T any] func(T) templ.Component
-type simplePage struct {
- dataFn dataFunc
- template string
-}
-
-func (p simplePage) ServeHTTP(w http.ResponseWriter, r *http.Request) {
- input := p.dataFn(r, userId(r))
- p.showTemplate(w, input)
-}
-
-func simpleByQuery[T any](tpl string, query func(ctx context.Context, id int32) (T, error)) Page {
- dataFn := func(r *http.Request, uid int32) any {
+func simpleByQuery[T any](tpl tplFunc[T], query func(ctx context.Context, id int32) (T, error)) Page {
+ dataFn := func(r *http.Request, uid int32) T {
d, _ := query(r.Context(), uid)
return d
}
return simple(tpl, dataFn)
}
-func simple(tpl string, dataFn dataFunc) Page {
- p := simplePage{dataFn, tpl}
+func simple[T any](tpl tplFunc[T], dataFn dataFunc[T]) Page {
r := chi.NewRouter()
- r.Get("/", p.ServeHTTP)
+ r.Get("/", func(w http.ResponseWriter, r *http.Request) {
+ input := dataFn(r, userId(r))
+ c := tpl(input)
+ render(c, w, r)
+ })
return r
}
-func showTemplate(w http.ResponseWriter, tpl string, data any) {
- if err := templ.Lookup(tpl).Execute(w, data); err != nil {
- log.Panicf("Executing '%s' with %+v: %v", tpl, data, err)
+type ctxPath struct{}
+
+func render(c templ.Component, w http.ResponseWriter, r *http.Request) {
+ ctx := context.WithValue(r.Context(), ctxPath{}, r.URL.Path)
+ if err := c.Render(ctx, w); err != nil {
+ log.Panic(err.Error())
}
}
-func (p simplePage) showTemplate(w http.ResponseWriter, data any) {
- showTemplate(w, p.template, data)
+func isCurrPath(ctx context.Context, path string) bool {
+ currPath := ctx.Value(ctxPath{}).(string)
+ if path[0] != '/' {
+ path = "/" + path
+ }
+
+ if currPath == "/" {
+ return path == "/"
+ }
+
+ if currPath[len(currPath)-1] == '/' {
+ currPath = currPath[:len(currPath)-1]
+ }
+
+ if path[len(path)-1] == '/' {
+ path = path[:len(path)-1]
+ }
+
+ return currPath == path
}