Skip to content

Commit

Permalink
Disable HTML escaping in InterfaceMarshalFunc. (#568)
Browse files Browse the repository at this point in the history
  • Loading branch information
mitar authored Mar 2, 2024
1 parent dfd022f commit 0d16f63
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
19 changes: 17 additions & 2 deletions globals.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package zerolog

import (
"bytes"
"encoding/json"
"strconv"
"sync/atomic"
Expand Down Expand Up @@ -81,8 +82,22 @@ var (
}

// InterfaceMarshalFunc allows customization of interface marshaling.
// Default: "encoding/json.Marshal"
InterfaceMarshalFunc = json.Marshal
// Default: "encoding/json.Marshal" with disabled HTML escaping
InterfaceMarshalFunc = func(v interface{}) ([]byte, error) {
var buf bytes.Buffer
encoder := json.NewEncoder(&buf)
encoder.SetEscapeHTML(false)
err := encoder.Encode(v)
if err != nil {
return nil, err
}
b := buf.Bytes()
if len(b) > 0 {
// Remove trailing \n which is added by Encode.
return b[:len(b)-1], nil
}
return b, nil
}

// TimeFieldFormat defines the time format of the Time field type. If set to
// TimeFormatUnix, TimeFormatUnixMs, TimeFormatUnixMicro or TimeFormatUnixNano, the time is formatted as a UNIX
Expand Down
9 changes: 9 additions & 0 deletions log_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1013,3 +1013,12 @@ func TestUnmarshalTextLevel(t *testing.T) {
})
}
}

func TestHTMLNoEscaping(t *testing.T) {
out := &bytes.Buffer{}
log := New(out)
log.Log().Interface("head", "<test>").Send()
if got, want := decodeIfBinaryToString(out.Bytes()), `{"head":"<test>"}`+"\n"; got != want {
t.Errorf("invalid log output:\ngot: %v\nwant: %v", got, want)
}
}

0 comments on commit 0d16f63

Please sign in to comment.