1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
|
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
}
|