From 1e9514f3c4225f67836f9b67cd68e97f45087325 Mon Sep 17 00:00:00 2001 From: "Sebastien Rosset (serosset)" Date: Thu, 14 Sep 2017 09:02:52 -0700 Subject: [PATCH 1/8] Add MarshalWithOpts method to have fine-grained control over data masking --- src/encoding/json/encode.go | 41 ++++++++++++++++++++++++++++++++++++- 1 file changed, 40 insertions(+), 1 deletion(-) diff --git a/src/encoding/json/encode.go b/src/encoding/json/encode.go index 9a2f84133544f7..de0b729367dc2c 100644 --- a/src/encoding/json/encode.go +++ b/src/encoding/json/encode.go @@ -181,6 +181,31 @@ func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) { return buf.Bytes(), nil } +// MarshalWithOpts is like Marshal but applies custom Marshalling, including data masking and indentation to format the output. +// The Opts interface specifies methods to control: +// - Output prefix and indentation options +// - Omitting empty values (e.g. empty strings) +// - Custom data masking to have fine-grained control over which specific fields are omitted during serialization. +// Each JSON element in the output will begin on a new line beginning with prefix +// followed by one or more copies of indent according to the indentation nesting. +func MarshalWithOpts(v interface{}, opts Opts) ([]byte, error) { + e := &encodeState{} + err := e.marshal(v, encOpts{escapeHTML: true, optx: opts}) + if err != nil { + return nil, err + } + if opts.Indent() != "" { + var buf bytes.Buffer + err = Indent(&buf, e.Bytes(), opts.Prefix(), opts.Indent()) + if err != nil { + return nil, err + } + return buf.Bytes(), nil + } else { + return e.Bytes(), nil + } +} + // HTMLEscape appends to dst the JSON-encoded src with <, >, &, U+2028 and U+2029 // characters inside string literals changed to \u003c, \u003e, \u0026, \u2028, \u2029 // so that the JSON will be safe to embed inside HTML