-
Notifications
You must be signed in to change notification settings - Fork 1
/
makehtmlgetter.go
77 lines (63 loc) · 2.13 KB
/
makehtmlgetter.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
package jaws
import (
"fmt"
"html"
"html/template"
)
type htmlGetter struct{ v template.HTML }
func (g htmlGetter) JawsGetHTML(e *Element) template.HTML {
return g.v
}
func (g htmlGetter) JawsGetTag(rq *Request) any {
return nil
}
type htmlStringerGetter struct{ sg fmt.Stringer }
func (g htmlStringerGetter) JawsGetHTML(e *Element) template.HTML {
return template.HTML(html.EscapeString(g.sg.String())) // #nosec G203
}
func (g htmlStringerGetter) JawsGetTag(rq *Request) any {
return g.sg
}
type htmlGetterString struct{ sg Getter[string] }
func (g htmlGetterString) JawsGetHTML(e *Element) template.HTML {
return template.HTML(html.EscapeString(g.sg.JawsGet(e))) // #nosec G203
}
func (g htmlGetterString) JawsGetTag(rq *Request) any {
return g.sg
}
type htmlGetterAny struct{ ag AnyGetter }
func (g htmlGetterAny) JawsGetHTML(e *Element) template.HTML {
s := fmt.Sprint(g.ag.JawsGetAny(e))
return template.HTML(html.EscapeString(s)) // #nosec G203
}
func (g htmlGetterAny) JawsGetTag(rq *Request) any {
return g.ag
}
// MakeHTMLGetter returns a HTMLGetter for v.
//
// Depending on the type of v, we return:
//
// - jaws.HTMLGetter: `JawsGetHTML(e *Element) template.HTML` to be used as-is.
// - jaws.Getter[string]: `JawsGet(elem *Element) string` that will be escaped using `html.EscapeString`.
// - jaws.AnyGetter: `JawsGetAny(elem *Element) any` that will be rendered using `fmt.Sprint()` and escaped using `html.EscapeString`.
// - fmt.Stringer: `String() string` that will be escaped using `html.EscapeString`.
// - a static `template.HTML` or `string` to be used as-is with no HTML escaping.
// - everything else is rendered using `fmt.Sprint()` and escaped using `html.EscapeString`.
func MakeHTMLGetter(v any) HTMLGetter {
switch v := v.(type) {
case HTMLGetter:
return v
case Getter[string]:
return htmlGetterString{v}
case AnyGetter:
return htmlGetterAny{v}
case fmt.Stringer:
return htmlStringerGetter{v}
case template.HTML:
return htmlGetter{v}
case string:
return htmlGetter{template.HTML(v)} // #nosec G203
default:
return htmlGetter{template.HTML(html.EscapeString(fmt.Sprint(v)))} // #nosec G203
}
}