diff options
Diffstat (limited to 'pages/page.go')
-rw-r--r-- | pages/page.go | 45 |
1 files changed, 30 insertions, 15 deletions
diff --git a/pages/page.go b/pages/page.go index 6ce8cee..c10fb21 100644 --- a/pages/page.go +++ b/pages/page.go @@ -20,38 +20,53 @@ type Page interface { http.Handler } -type dataFunc[T any] func(r *http.Request, uid int32) T +type dataFunc[T any] func(ctx context.Context) T type tplFunc[T any] func(T) templ.Component -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(c templ.Component) Page { + r := chi.NewRouter() + r.Get("/", render(c)) + return r } -func simple[T any](tpl tplFunc[T], dataFn dataFunc[T]) Page { +func simpleWithData[T any](tpl tplFunc[T], dataFn dataFunc[T]) Page { r := chi.NewRouter() r.Get("/", func(w http.ResponseWriter, r *http.Request) { - input := dataFn(r, userId(r)) + input := dataFn(r.Context()) c := tpl(input) - render(c, w, r) + render(c)(w, r) }) return r } +func simpleByQuery[T any](tpl tplFunc[T], query func(context.Context, int32) (T, error)) Page { + dataFn := func(ctx context.Context) T { + d, err := query(ctx, getUser(ctx).ID) + if err != nil { + log.Panic(err.Error()) + } + return d + } + return simpleWithData(tpl, dataFn) +} + 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 render(c templ.Component) http.HandlerFunc { + return func(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 getCurrPath(ctx context.Context) string { + return ctx.Value(ctxPath{}).(string) +} + func isCurrPath(ctx context.Context, path string) bool { - currPath := ctx.Value(ctxPath{}).(string) + currPath := getCurrPath(ctx) if path[0] != '/' { path = "/" + path } |