Skip to content

Commit 0d16f63

Browse files
authored
Disable HTML escaping in InterfaceMarshalFunc. (#568)
1 parent dfd022f commit 0d16f63

File tree

2 files changed

+26
-2
lines changed

2 files changed

+26
-2
lines changed

globals.go

+17-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package zerolog
22

33
import (
4+
"bytes"
45
"encoding/json"
56
"strconv"
67
"sync/atomic"
@@ -81,8 +82,22 @@ var (
8182
}
8283

8384
// InterfaceMarshalFunc allows customization of interface marshaling.
84-
// Default: "encoding/json.Marshal"
85-
InterfaceMarshalFunc = json.Marshal
85+
// Default: "encoding/json.Marshal" with disabled HTML escaping
86+
InterfaceMarshalFunc = func(v interface{}) ([]byte, error) {
87+
var buf bytes.Buffer
88+
encoder := json.NewEncoder(&buf)
89+
encoder.SetEscapeHTML(false)
90+
err := encoder.Encode(v)
91+
if err != nil {
92+
return nil, err
93+
}
94+
b := buf.Bytes()
95+
if len(b) > 0 {
96+
// Remove trailing \n which is added by Encode.
97+
return b[:len(b)-1], nil
98+
}
99+
return b, nil
100+
}
86101

87102
// TimeFieldFormat defines the time format of the Time field type. If set to
88103
// TimeFormatUnix, TimeFormatUnixMs, TimeFormatUnixMicro or TimeFormatUnixNano, the time is formatted as a UNIX

log_test.go

+9
Original file line numberDiff line numberDiff line change
@@ -1013,3 +1013,12 @@ func TestUnmarshalTextLevel(t *testing.T) {
10131013
})
10141014
}
10151015
}
1016+
1017+
func TestHTMLNoEscaping(t *testing.T) {
1018+
out := &bytes.Buffer{}
1019+
log := New(out)
1020+
log.Log().Interface("head", "<test>").Send()
1021+
if got, want := decodeIfBinaryToString(out.Bytes()), `{"head":"<test>"}`+"\n"; got != want {
1022+
t.Errorf("invalid log output:\ngot: %v\nwant: %v", got, want)
1023+
}
1024+
}

0 commit comments

Comments
 (0)