package pages import ( "context" "gosten/model" "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(ctx context.Context) T type tplFunc[T any] func(T) templ.Component func simple(c templ.Component) Page { r := chi.NewRouter() r.Get("/", render(c)) return r } 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.Context()) c := tpl(input) 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 { panic(err.Error()) } return d } return simpleWithData(tpl, dataFn) } type ctxPath struct{} 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 { panic(err.Error()) } } } func getCurrPath(ctx context.Context) string { return ctx.Value(ctxPath{}).(string) } func isCurrPath(ctx context.Context, path string) bool { currPath := getCurrPath(ctx) 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 }