From ab52ad894f453a02153fb2bc106d08c47ba643b6 Mon Sep 17 00:00:00 2001 From: Caleb Spare Date: Sat, 9 Apr 2016 21:18:22 -0700 Subject: encoding/json: add Encoder.DisableHTMLEscaping This provides a way to disable the escaping of <, >, and & in JSON strings. Fixes #14749. Change-Id: I1afeb0244455fc8b06c6cce920444532f229555b Reviewed-on: https://go-review.googlesource.com/21796 Run-TryBot: Caleb Spare TryBot-Result: Gobot Gobot Reviewed-by: Brad Fitzpatrick --- src/encoding/json/stream.go | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) (limited to 'src/encoding/json/stream.go') diff --git a/src/encoding/json/stream.go b/src/encoding/json/stream.go index 422837bb63..d6b2992e9b 100644 --- a/src/encoding/json/stream.go +++ b/src/encoding/json/stream.go @@ -166,8 +166,9 @@ func nonSpace(b []byte) bool { // An Encoder writes JSON values to an output stream. type Encoder struct { - w io.Writer - err error + w io.Writer + err error + escapeHTML bool indentBuf *bytes.Buffer indentPrefix string @@ -176,7 +177,7 @@ type Encoder struct { // NewEncoder returns a new encoder that writes to w. func NewEncoder(w io.Writer) *Encoder { - return &Encoder{w: w} + return &Encoder{w: w, escapeHTML: true} } // Encode writes the JSON encoding of v to the stream, @@ -189,7 +190,7 @@ func (enc *Encoder) Encode(v interface{}) error { return enc.err } e := newEncodeState() - err := e.marshal(v) + err := e.marshal(v, encOpts{escapeHTML: enc.escapeHTML}) if err != nil { return err } @@ -225,6 +226,12 @@ 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 +} + // RawMessage is a raw encoded JSON value. // It implements Marshaler and Unmarshaler and can // be used to delay JSON decoding or precompute a JSON encoding. -- cgit v1.3-5-g9baa