/
theme.go
102 lines (83 loc) · 1.81 KB
/
theme.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
package render
import (
"context"
"net/http"
)
type Theme uint8
const (
LightTheme Theme = iota
DarkTheme
NordTheme // also light
// reserved for internal use
themeLen
)
const DefaultTheme = LightTheme
func ParseTheme(name string) Theme {
switch name {
case "light":
return LightTheme
case "dark":
return DarkTheme
case "nord":
return NordTheme
}
return DefaultTheme
}
func (t Theme) String() string {
switch t {
case LightTheme:
return "light"
case DarkTheme:
return "dark"
case NordTheme:
fallthrough
default:
return "nord"
}
}
func (t Theme) URL() string {
switch t {
case LightTheme:
return "https://minicss.org/flavorFiles/mini-default.min.css"
case DarkTheme:
return "https://minicss.org/flavorFiles/mini-dark.min.css"
case NordTheme:
return "https://minicss.org/flavorFiles/mini-nord.min.css"
}
return ""
}
type _renderctx struct{}
var renderctxkey = _renderctx{}
func ThemeM(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var theme = DefaultTheme
if c, err := r.Cookie("theme"); err == nil {
switch c.Value {
case "light":
theme = LightTheme
case "dark":
theme = DarkTheme
case "nord":
theme = NordTheme
}
}
next.ServeHTTP(
w,
r.WithContext(context.WithValue(r.Context(), renderctxkey, theme)),
)
})
}
func GetTheme(ctx context.Context) Theme {
if v, ok := ctx.Value(renderctxkey).(Theme); ok {
return v
}
return DefaultTheme
}
func SetThemeCookie(w http.ResponseWriter, theme Theme) {
SetWeakCookie(w, "theme", theme.String())
}
func handleSetTheme(w http.ResponseWriter, r *http.Request) {
SetThemeCookie(w, ParseTheme(r.FormValue("theme")))
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Redirections
http.Redirect(w, r, r.Referer(), http.StatusSeeOther)
}