From 10bf744772c0cfae8ea0e9f34adb7afec3d03a72 Mon Sep 17 00:00:00 2001 From: Mike Samuel Date: Mon, 26 Sep 2011 02:10:43 -0700 Subject: [PATCH] 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 --- src/pkg/exp/template/html/escape_test.go | 29 ++++++++++- src/pkg/exp/template/html/js.go | 61 +++++++++++++++++------- src/pkg/exp/template/html/js_test.go | 47 +++++++++++++++++- 3 files changed, 116 insertions(+), 21 deletions(-) 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) { "