From: Russ Cox Date: Mon, 23 May 2016 15:41:00 +0000 (-0400) Subject: encoding/json: change DisableHTMLEscaping to SetEscapeHTML X-Git-Tag: go1.7beta1~119 X-Git-Url: http://www.git.cypherpunks.su/?a=commitdiff_plain;h=4aea7a12b6a6621a67267050df0688f28adfe6b4;p=gostls13.git encoding/json: change DisableHTMLEscaping to SetEscapeHTML DisableHTMLEscaping is now SetEscapeHTML, allowing the escaping to be toggled, not just disabled. This API is new for Go 1.7, so there are no compatibility concerns (quite the opposite, the point is to fix the API before we commit to it in Go 1.7). Change-Id: I96b9f8f169a9c44995b8a157a626eb62d0b6dea7 Reviewed-on: https://go-review.googlesource.com/23293 Reviewed-by: Ian Lance Taylor Reviewed-by: Andrew Gerrand --- diff --git a/src/encoding/json/stream.go b/src/encoding/json/stream.go index d6b2992e9b..dba978aa66 100644 --- a/src/encoding/json/stream.go +++ b/src/encoding/json/stream.go @@ -226,10 +226,15 @@ func (enc *Encoder) Indent(prefix, indent string) { enc.indentValue = indent } -// DisableHTMLEscaping causes the encoder not to escape angle brackets -// ("<" and ">") or ampersands ("&") in JSON strings. -func (enc *Encoder) DisableHTMLEscaping() { - enc.escapeHTML = false +// SetEscapeHTML specifies whether problematic HTML characters +// should be escaped inside JSON quoted strings. +// The default behavior is to escape &, <, and > to \u0026, \u003c, and \u003e +// to avoid certain safety problems that can arise when embedding JSON in HTML. +// +// In non-HTML settings where the escaping interferes with the readability +// of the output, SetEscapeHTML(false) disables this behavior. +func (enc *Encoder) SetEscapeHTML(on bool) { + enc.escapeHTML = on } // RawMessage is a raw encoded JSON value. diff --git a/src/encoding/json/stream_test.go b/src/encoding/json/stream_test.go index 3516ac3b83..0d578ce24d 100644 --- a/src/encoding/json/stream_test.go +++ b/src/encoding/json/stream_test.go @@ -87,7 +87,7 @@ func TestEncoderIndent(t *testing.T) { } } -func TestEncoderDisableHTMLEscaping(t *testing.T) { +func TestEncoderSetEscapeHTML(t *testing.T) { var c C var ct CText for _, tt := range []struct { @@ -109,12 +109,12 @@ func TestEncoderDisableHTMLEscaping(t *testing.T) { t.Errorf("Encode(%s) = %#q, want %#q", tt.name, got, tt.wantEscape) } buf.Reset() - enc.DisableHTMLEscaping() + enc.SetEscapeHTML(false) if err := enc.Encode(tt.v); err != nil { - t.Fatalf("DisableHTMLEscaping Encode(%s): %s", tt.name, err) + t.Fatalf("SetEscapeHTML(false) Encode(%s): %s", tt.name, err) } if got := strings.TrimSpace(buf.String()); got != tt.want { - t.Errorf("DisableHTMLEscaping Encode(%s) = %#q, want %#q", + t.Errorf("SetEscapeHTML(false) Encode(%s) = %#q, want %#q", tt.name, got, tt.want) } }