-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcontext.go
107 lines (87 loc) · 2.36 KB
/
context.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package torque
import (
"context"
"github.com/gorilla/schema"
"net/http"
)
type contextKey string
const (
titleKey contextKey = "title"
errorKey contextKey = "error"
decoderKey contextKey = "decoder"
modeKey contextKey = "mode"
scriptsKey contextKey = "scripts"
// internal keys
paramsContextKey contextKey = "params"
outletContextKey contextKey = "outlet-flow"
)
type Mode string
const (
ModeDevelopment Mode = "development"
ModeProduction Mode = "production"
)
func With[T any](req *http.Request, key any, value *T) {
*req = *req.WithContext(context.WithValue(req.Context(), key, value))
}
func Use[T any](req *http.Request, key any) *T {
if value, ok := req.Context().Value(key).(T); ok {
return &value
}
return nil
}
func withError(ctx context.Context, err error) context.Context {
return context.WithValue(ctx, errorKey, err)
}
func UseError(ctx context.Context) error {
if err, ok := ctx.Value(errorKey).(error); ok {
return err
}
return nil
}
func withDecoder(ctx context.Context, d *schema.Decoder) context.Context {
return context.WithValue(ctx, decoderKey, d)
}
func UseDecoder(ctx context.Context) *schema.Decoder {
if d, ok := ctx.Value(decoderKey).(*schema.Decoder); ok {
return d
}
return nil
}
func WithMode(ctx context.Context, mode Mode) context.Context {
return context.WithValue(ctx, modeKey, mode)
}
func UseMode(ctx context.Context) Mode {
if mode, ok := ctx.Value(modeKey).(Mode); ok {
return mode
}
return ModeProduction
}
// WithTitle sets the page title in the request context.
func WithTitle(req *http.Request, title string) {
*req = *req.WithContext(context.WithValue(req.Context(), titleKey, title))
}
// UseTitle returns the page title set in the request context.
func UseTitle(req *http.Request) string {
if title, ok := req.Context().Value(titleKey).(string); ok {
return title
}
return ""
}
func WithScript(req *http.Request, script string) {
var scripts, ok = req.Context().Value(scriptsKey).([]string)
if !ok {
scripts = []string{script}
} else {
scripts = append(scripts, script)
}
*req = *req.WithContext(context.WithValue(req.Context(), scriptsKey, scripts))
}
func UseScripts(req *http.Request) []string {
if scripts, ok := req.Context().Value(scriptsKey).([]string); ok {
return scripts
}
return nil
}
func UseTarget(req *http.Request) string {
return req.Header.Get("X-Torque-Target")
}