esc.go

 1package html
 2
 3import (
 4	"html"
 5	"io"
 6)
 7
 8var Escaper = [256][]byte{
 9	'&': []byte("&"),
10	'<': []byte("&lt;"),
11	'>': []byte("&gt;"),
12	'"': []byte("&quot;"),
13}
14
15// EscapeHTML writes html-escaped d to w. It escapes &, <, > and " characters.
16func EscapeHTML(w io.Writer, d []byte) {
17	var start, end int
18	n := len(d)
19	for end < n {
20		escSeq := Escaper[d[end]]
21		if escSeq != nil {
22			w.Write(d[start:end])
23			w.Write(escSeq)
24			start = end + 1
25		}
26		end++
27	}
28	if start < n && end <= n {
29		w.Write(d[start:end])
30	}
31}
32
33func escLink(w io.Writer, text []byte) {
34	unesc := html.UnescapeString(string(text))
35	EscapeHTML(w, []byte(unesc))
36}
37
38// Escape writes the text to w, but skips the escape character.
39func Escape(w io.Writer, text []byte) {
40	esc := false
41	for i := 0; i < len(text); i++ {
42		if text[i] == '\\' {
43			esc = !esc
44		}
45		if esc && text[i] == '\\' {
46			continue
47		}
48		w.Write([]byte{text[i]})
49	}
50}