-
Notifications
You must be signed in to change notification settings - Fork 6
/
html.go
executable file
·77 lines (63 loc) · 2.14 KB
/
html.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 helpers
import (
"fmt"
"strings"
got "html/template"
"github.com/kennygrant/sanitize"
)
// Style inserts a css tag
func Style(name string) got.HTML {
return got.HTML(fmt.Sprintf("<link href=\"/assets/styles/%s.css\" media=\"all\" rel=\"stylesheet\" type=\"text/css\" />", EscapeURL(name)))
}
// Script inserts a script tag
func Script(name string) got.HTML {
return got.HTML(fmt.Sprintf("<script src=\"/assets/scripts/%s.js\" type=\"text/javascript\"></script>", EscapeURL(name)))
}
// Escape escapes HTML using HTMLEscapeString
func Escape(s string) string {
return got.HTMLEscapeString(s)
}
// EscapeURL escapes URLs using HTMLEscapeString
func EscapeURL(s string) string {
return got.URLQueryEscaper(s)
}
// Link returns got.HTML with an anchor link given text and URL required
// Attributes (if supplied) should not contain user input
func Link(t string, u string, a ...string) got.HTML {
attributes := ""
if len(a) > 0 {
attributes = strings.Join(a, " ")
}
return got.HTML(fmt.Sprintf("<a href=\"%s\" %s>%s</a>", Escape(u), Escape(attributes), Escape(t)))
}
// HTML returns a string (which must not contain user input) as go template HTML
func HTML(s string) got.HTML {
return got.HTML(s)
}
// HTMLAttribute returns a string (which must not contain user input) as go template HTMLAttr
func HTMLAttribute(s string) got.HTMLAttr {
return got.HTMLAttr(s)
}
// URL returns returns a string (which must not contain user input) as go template URL
func URL(s string) got.URL {
return got.URL(s)
}
// Strip all html tags and returns as go template HTML
func Strip(s string) got.HTML {
return got.HTML(sanitize.HTML(s))
}
// Sanitize the html, leaving only tags we consider safe (see the sanitize package for details and tests)
func Sanitize(s string) got.HTML {
s, err := sanitize.HTMLAllowing(s)
if err != nil {
fmt.Printf("#error sanitizing html:%s", err)
return got.HTML("")
}
return got.HTML(s)
}
// XMLPreamble returns an XML preamble as got.HTML,
// primarily to work around a bug in html/template which escapes <?
// see https://github.com/golang/go/issues/12496
func XMLPreamble() got.HTML {
return `<?xml version="1.0" encoding="UTF-8"?>`
}