From: Micah Stetson Date: Mon, 12 Jul 2010 18:26:41 +0000 (-0700) Subject: json: Add HTMLEscape X-Git-Tag: weekly.2010-07-14~33 X-Git-Url: http://www.git.cypherpunks.su/?a=commitdiff_plain;h=b5b6ce08043daf13f22e4250d3bafea7eb826eda;p=gostls13.git json: Add HTMLEscape R=rsc CC=golang-dev https://golang.org/cl/1496042 --- diff --git a/src/pkg/json/decode_test.go b/src/pkg/json/decode_test.go index e10b2c56e6..d5ab29ca64 100644 --- a/src/pkg/json/decode_test.go +++ b/src/pkg/json/decode_test.go @@ -139,6 +139,16 @@ func TestUnmarshalPtrPtr(t *testing.T) { } } +func TestHTMLEscape(t *testing.T) { + b, err := MarshalForHTML("foobarbaz<>&quux") + if err != nil { + t.Fatalf("MarshalForHTML error: %v", err) + } + if !bytes.Equal(b, []byte(`"foobarbaz\u003c\u003e\u0026quux"`)) { + t.Fatalf("Unexpected encoding of \"<>&\": %s", b) + } +} + func noSpace(c int) int { if isSpace(c) { return -1 diff --git a/src/pkg/json/encode.go b/src/pkg/json/encode.go index 5d7ce35cbb..882ae0e70a 100644 --- a/src/pkg/json/encode.go +++ b/src/pkg/json/encode.go @@ -76,6 +76,43 @@ func MarshalIndent(v interface{}, prefix, indent string) ([]byte, os.Error) { return buf.Bytes(), nil } +// MarshalForHTML is like Marshal but applies HTMLEscape to the output. +func MarshalForHTML(v interface{}) ([]byte, os.Error) { + b, err := Marshal(v) + if err != nil { + return nil, err + } + var buf bytes.Buffer + HTMLEscape(&buf, b) + return buf.Bytes(), nil +} + +// HTMLEscape appends to dst the JSON-encoded src with <, >, and & +// characters inside string literals changed to \u003c, \u003e, \u0026 +// so that the JSON will be safe to embed inside HTML