-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhtml.go
50 lines (41 loc) · 1.37 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
package goutil
import (
"bytes"
"github.com/tkdeng/goregex"
)
type encodeHtml struct{}
var HTML *encodeHtml = &encodeHtml{}
var regEscHTML *regex.Regexp = regex.Comp(`[<>&]`)
var regEscFixAmp *regex.Regexp = regex.Comp(`&(amp;)*`)
// EscapeHTML replaces HTML characters with html entities
//
// Also prevents and removes &amp; from results
func (encHtml *encodeHtml) Escape(html []byte) []byte {
html = regEscHTML.RepFunc(html, func(data func(int) []byte) []byte {
if bytes.Equal(data(0), []byte("<")) {
return []byte("<")
} else if bytes.Equal(data(0), []byte(">")) {
return []byte(">")
}
return []byte("&")
})
return regEscFixAmp.RepStrLit(html, []byte("&"))
}
var regEscHTMLArgs *regex.Regexp = regex.Comp(`([\\]*)([\\"'\'])`)
// EscapeHTMLArgs escapes quotes and backslashes for use within HTML quotes
// @quote can be used to only escape specific quotes or chars
func (encHtml *encodeHtml) EscapeArgs(html []byte, quote ...byte) []byte {
if len(quote) == 0 {
quote = []byte("\"'`")
}
return regEscHTMLArgs.RepFunc(html, func(data func(int) []byte) []byte {
if len(data(1))%2 == 0 && bytes.ContainsRune(quote, rune(data(2)[0])) {
// return append([]byte("\\"), data(2)...)
return regex.JoinBytes(data(1), '\\', data(2))
}
if bytes.ContainsRune(quote, rune(data(2)[0])) {
return append(data(1), data(2)...)
}
return data(0)
})
}