From: Mike Samuel Date: Mon, 26 Sep 2011 09:10:43 +0000 (-0700) Subject: exp/template/html: make sure marshalled JSON can be parsed as JS. X-Git-Tag: weekly.2011-10-06~100 X-Git-Url: http://www.git.cypherpunks.su/?a=commitdiff_plain;h=10bf744772c0cfae8ea0e9f34adb7afec3d03a72;p=gostls13.git exp/template/html: make sure marshalled JSON can be parsed as JS. This makes sure that all JS newlines are encoded in JSON. It also moots a TODO about possibly escaping supplemental codepoints. I served: Content-Type: text/javascript;charset=UTF-8 var s = "%s"; document.write("

", s, "

    "); for (var i = 0; i < s.length; i++) { document.write("
  1. ", s.charCodeAt(i).toString(16), "
  2. "); } document.write(""); where %s was replaced with bytes "\xf0\x9d\x84\x9e" to test straight UTF-8 instead of encoding surrogates separately. Recent Firefox, Chrome, and Safari all decoded it properly. I have yet to try it on IE or older versions. R=nigeltao CC=golang-dev https://golang.org/cl/5129042 --- diff --git a/src/pkg/exp/template/html/escape_test.go b/src/pkg/exp/template/html/escape_test.go index da3c011961..ea7d3bdb04 100644 --- a/src/pkg/exp/template/html/escape_test.go +++ b/src/pkg/exp/template/html/escape_test.go @@ -7,6 +7,7 @@ package html import ( "bytes" "fmt" + "json" "os" "strings" "template" @@ -14,11 +15,25 @@ import ( "testing" ) +type badMarshaler struct{} + +func (x *badMarshaler) MarshalJSON() ([]byte, os.Error) { + // Keys in valid JSON must be double quoted as must all strings. + return []byte("{ foo: 'not quite valid JSON' }"), nil +} + +type goodMarshaler struct{} + +func (x *goodMarshaler) MarshalJSON() ([]byte, os.Error) { + return []byte(`{ "": "O'Reilly" }`), nil +} + func TestEscape(t *testing.T) { var data = struct { F, T bool C, G, H string A, E []string + B, M json.Marshaler N int Z *int W HTML @@ -31,6 +46,8 @@ func TestEscape(t *testing.T) { A: []string{"", ""}, E: []string{}, N: 42, + B: &badMarshaler{}, + M: &goodMarshaler{}, Z: nil, W: HTML(`¡Hello, !`), } @@ -195,6 +212,16 @@ func TestEscape(t *testing.T) { "