From daae07b7e65ad271cdfea857d9098ffc985f04f2 Mon Sep 17 00:00:00 2001 From: Erik Dubbelboer Date: Mon, 16 Jan 2017 06:23:14 +0000 Subject: [PATCH] Add NoEscapeHTML to jwriter.Writer This option is similar to json.Encoder.SetEscapeHTML. The default behavior of false is to escape &, <, and > to \u0026, \u003c, and \u003e. Setting this to true will not escape these. --- jwriter/writer.go | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/jwriter/writer.go b/jwriter/writer.go index a3ef534..04bfddf 100644 --- a/jwriter/writer.go +++ b/jwriter/writer.go @@ -23,8 +23,9 @@ const ( type Writer struct { Flags Flags - Error error - Buffer buffer.Buffer + Error error + Buffer buffer.Buffer + NoEscapeHTML bool } // Size returns the size of the data that was written out. @@ -225,10 +226,14 @@ func (w *Writer) Bool(v bool) { const chars = "0123456789abcdef" -func isNotEscapedSingleChar(c byte) bool { +func isNotEscapedSingleChar(c byte, escapeHTML bool) bool { // Note: might make sense to use a table if there are more chars to escape. With 4 chars // it benchmarks the same. - return c != '<' && c != '\\' && c != '"' && c != '>' && c >= 0x20 && c < utf8.RuneSelf + if escapeHTML { + return c != '<' && c != '>' && c != '&' && c != '\\' && c != '"' && c >= 0x20 && c < utf8.RuneSelf + } else { + return c != '\\' && c != '"' && c >= 0x20 && c < utf8.RuneSelf + } } func (w *Writer) String(s string) { @@ -242,7 +247,7 @@ func (w *Writer) String(s string) { for i := 0; i < len(s); { c := s[i] - if isNotEscapedSingleChar(c) { + if isNotEscapedSingleChar(c, !w.NoEscapeHTML) { // single-width character, no escaping is required i++ continue