-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.go
81 lines (67 loc) · 1.81 KB
/
util.go
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
73
74
75
76
77
78
79
80
81
package gong
import (
"context"
"encoding/json"
"fmt"
"hash/fnv"
"io"
"net/http"
"strconv"
"github.com/a-h/templ"
)
func getContext(ctx context.Context) gongContext {
return ctx.Value(contextKey).(gongContext)
}
func Bind(ctx context.Context, dest any) error {
gCtx := getContext(ctx)
if err := json.NewDecoder(gCtx.request.Body).Decode(dest); err != nil {
return err
}
return nil
}
func GetParam(ctx context.Context, key string) string {
gCtx := getContext(ctx)
return gCtx.request.FormValue(key)
}
func buildComponentID(ctx context.Context, id string) string {
gCtx := getContext(ctx)
prefix := "gong" + "_" + hash(gCtx.route.path)
if gCtx.kind != "" {
prefix += "_" + gCtx.kind
}
if id != "" {
prefix += "_" + id
}
return prefix
}
func buildOutletID(ctx context.Context) string {
gCtx := getContext(ctx)
return "gong" + "_" + hash(gCtx.route.path) + "_outlet"
}
func buildHeaders(ctx context.Context, requestType string) string {
gCtx := getContext(ctx)
return fmt.Sprintf(`{"%s": "%s", "%s": "%s", "%s": "%s"}`, GongRequestHeader, requestType, GongRouteHeader, gCtx.route.path, GongKindHeader, gCtx.kind)
}
func GetRequest(ctx context.Context) *http.Request {
return getContext(ctx).request
}
func GetLoaderData[Data any](ctx context.Context) (data Data) {
gCtx := getContext(ctx)
if gCtx.loader == nil {
return data
}
return gCtx.loader.Loader(ctx).(Data)
}
func render(ctx context.Context, gCtx gongContext, w io.Writer, component templ.Component) error {
ctx = context.WithValue(ctx, contextKey, gCtx)
return component.Render(ctx, w)
}
func hash(s string) string {
h := fnv.New32a()
h.Write([]byte(s))
return strconv.Itoa(int(h.Sum32()))
}
type RenderFunc func(ctx context.Context, w io.Writer) error
func (r RenderFunc) Render(ctx context.Context, w io.Writer) error {
return r(ctx, w)
}