This commit is contained in:
2023-05-05 14:43:40 +02:00
parent a445e6f623
commit cecfb0d788
2 changed files with 61 additions and 2 deletions

View File

@@ -167,15 +167,30 @@ func Marshal(v any) ([]byte, error) {
return buf, nil
}
type IndentOpt struct {
Prefix string
Indent string
}
// MarshalSafeCollections is like Marshal except it will marshal nil maps and
// slices as '{}' and '[]' respectfully instead of 'null'
func MarshalSafeCollections(v interface{}, nilSafeSlices bool, nilSafeMaps bool) ([]byte, error) {
func MarshalSafeCollections(v interface{}, nilSafeSlices bool, nilSafeMaps bool, indent *IndentOpt) ([]byte, error) {
e := &encodeState{}
err := e.marshal(v, encOpts{escapeHTML: true, nilSafeSlices: nilSafeSlices, nilSafeMaps: nilSafeMaps})
if err != nil {
return nil, err
}
return e.Bytes(), nil
b := e.Bytes()
if indent != nil {
var buf bytes.Buffer
err = Indent(&buf, b, indent.Prefix, indent.Indent)
if err != nil {
return nil, err
}
return buf.Bytes(), nil
} else {
return e.Bytes(), nil
}
}
// MarshalIndent is like Marshal but applies Indent to format the output.