Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix AppendHTMLEscape #1248

Merged
merged 1 commit into from Mar 15, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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