package pages import ( "context" "gosten/model" "log" "net/http" "github.com/a-h/templ" "github.com/go-chi/chi/v5" ) var Q *model.Queries func Connect(tx model.DBTX) { Q = model.New(tx) } type Page interface { http.Handler } type dataFunc[T any] func(r *http.Request, uid int32) 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[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)) c := tpl(input) render(c, w, r) }) return r } 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 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 }