Skip to content

Commit

Permalink
Fix AppendHTMLEscape (#1248)
Browse files Browse the repository at this point in the history
  • Loading branch information
zhangyunhao116 committed Mar 15, 2022
1 parent 1a5f2f4 commit f7423e3
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
9 changes: 6 additions & 3 deletions bytesconv.go
Expand Up @@ -19,7 +19,8 @@ import (

// AppendHTMLEscape appends html-escaped s to dst and returns the extended dst.
func AppendHTMLEscape(dst []byte, s string) []byte {
if strings.IndexByte(s, '<') < 0 &&
if strings.IndexByte(s, '&') < 0 &&
strings.IndexByte(s, '<') < 0 &&
strings.IndexByte(s, '>') < 0 &&
strings.IndexByte(s, '"') < 0 &&
strings.IndexByte(s, '\'') < 0 {
Expand All @@ -34,14 +35,16 @@ func AppendHTMLEscape(dst []byte, s string) []byte {
for i, n := 0, len(s); i < n; i++ {
sub = ""
switch s[i] {
case '&':
sub = "&amp;"
case '<':
sub = "&lt;"
case '>':
sub = "&gt;"
case '"':
sub = "&quot;"
sub = "&#34;" // "&#34;" is shorter than "&quot;".
case '\'':
sub = "&#39;"
sub = "&#39;" // "&#39;" is shorter than "&apos;" and apos was not in HTML until HTML5.
}
if len(sub) > 0 {
dst = append(dst, s[prev:i]...)
Expand Down
14 changes: 13 additions & 1 deletion bytesconv_test.go
Expand Up @@ -4,6 +4,7 @@ import (
"bufio"
"bytes"
"fmt"
"html"
"net"
"testing"
"time"
Expand All @@ -14,10 +15,21 @@ import (
func TestAppendHTMLEscape(t *testing.T) {
t.Parallel()

// Sync with html.EscapeString
allcases := make([]byte, 256)
for i := 0; i < 256; i++ {
allcases[i] = byte(i)
}
res := string(AppendHTMLEscape(nil, string(allcases)))
expect := string(html.EscapeString(string(allcases)))
if res != expect {
t.Fatalf("unexpected string %q. Expecting %q.", res, expect)
}

testAppendHTMLEscape(t, "", "")
testAppendHTMLEscape(t, "<", "&lt;")
testAppendHTMLEscape(t, "a", "a")
testAppendHTMLEscape(t, `><"''`, "&gt;&lt;&quot;&#39;&#39;")
testAppendHTMLEscape(t, `><"''`, "&gt;&lt;&#34;&#39;&#39;")
testAppendHTMLEscape(t, "fo<b x='ss'>a</b>xxx", "fo&lt;b x=&#39;ss&#39;&gt;a&lt;/b&gt;xxx")
}

Expand Down

0 comments on commit f7423e3

Please sign in to comment.