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 <iant@golang.org>
Reviewed-by: Andrew Gerrand <adg@golang.org>
This commit is contained in:
Russ Cox 2016-05-23 11:41:00 -04:00
parent 658814fa38
commit 4aea7a12b6
2 changed files with 13 additions and 8 deletions

View File

@ -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.

View File

@ -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)
}
}