Skip to content

Commit

Permalink
Add reflect support for json.Marshaler
Browse files Browse the repository at this point in the history
Signed-off-by: Matthew Sykes <[email protected]>
  • Loading branch information
sykesm committed Sep 22, 2020
1 parent 1666602 commit 30c7ed3
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 7 deletions.
9 changes: 4 additions & 5 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,11 @@ language: go

matrix:
include:
- go: "1.12.x"
install: true
env: GO111MODULE=on
- go: "1.13.x"
env: GO111MODULE=off
- go: "1.13.x"
install: true
- go: "1.14.x"
install: true
- go: "1.15.x"
install: true

script: go test -race ./...
7 changes: 7 additions & 0 deletions encoder.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"bytes"
"encoding"
"encoding/base64"
"encoding/json"
"fmt"
"math"
"reflect"
Expand Down Expand Up @@ -249,6 +250,12 @@ func (enc *logfmtEncoder) AppendReflected(value interface{}) error {
return err
}
enc.AppendString(string(b))
case json.Marshaler:
b, err := v.MarshalJSON()
if err != nil {
return err
}
enc.AppendString(string(b))
default:
rvalue := reflect.ValueOf(value)
switch rvalue.Kind() {
Expand Down
7 changes: 5 additions & 2 deletions encoder_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -150,9 +150,11 @@ func TestEncoderSimple(t *testing.T) {

type stringer string
type textMarshaler string
type jsonMarshaler string

func (s stringer) String() string { return string(s) }
func (t textMarshaler) MarshalText() ([]byte, error) { return []byte(t), nil }
func (j jsonMarshaler) MarshalJSON() ([]byte, error) { return []byte(j), nil }

func TestEncoderReflected(t *testing.T) {
dummyFunc := func(string) {}
Expand All @@ -168,6 +170,7 @@ func TestEncoderReflected(t *testing.T) {
{"bytes", "bytes", []byte("bytes")},
{"stringer", "my-stringer", stringer("my-stringer")},
{"text marshaler", "marshaled-text", textMarshaler("marshaled-text")},
{"json marshaler", `"{\"json\":\"data\"}"`, textMarshaler(`{"json":"data"}`)},
{"bool", "true", true},
{"int", "-1", -int(1)},
{"int8", "-8", int8(-8)},
Expand Down Expand Up @@ -322,7 +325,7 @@ func TestArrayEncoderComplex(t *testing.T) {
f: func(enc zapcore.ArrayEncoder) error {
for i := 0; i < 3; i++ {
enc.AppendObject(zapcore.ObjectMarshalerFunc(func(oe zapcore.ObjectEncoder) error {
oe.AddInt(string('a'+i), i)
oe.AddInt(string(rune('a'+i)), i)
return nil
}))
}
Expand Down Expand Up @@ -431,7 +434,7 @@ func TestObjectEncoderComplex(t *testing.T) {
for i := 0; i < 3; i++ {
enc.AddObject(strconv.Itoa(i), zapcore.ObjectMarshalerFunc(func(oe zapcore.ObjectEncoder) error {
for j := 0; j < 3; j++ {
oe.AddInt(string('a'+i*3+j), i*3+j+1)
oe.AddInt(string(rune('a'+i*3+j)), i*3+j+1)
}
return nil
}))
Expand Down

0 comments on commit 30c7ed3

Please sign in to comment.