Skip to content

Commit

Permalink
Fix marshalling TextMarshaler and Stringer
Browse files Browse the repository at this point in the history
Fixes #7 by not marshalling those cases and let json.Marshal do it's job
instead.
  • Loading branch information
mweibel committed Dec 4, 2017
1 parent a9bc0eb commit 0ae0e1f
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 3 deletions.
9 changes: 6 additions & 3 deletions sheriff.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package sheriff

import (
"encoding"
"encoding/json"
"fmt"
"reflect"
Expand Down Expand Up @@ -157,9 +158,11 @@ func marshalValue(options *Options, v reflect.Value) (interface{}, error) {
if marshaller, ok := val.(Marshaller); ok {
return marshaller.Marshal(options)
}
// TODO(mweibel): This is a hack for struct types which conform to json.Marshaler (such as time.Time).
// This makes sure those struct types aren't marshalled by sheriff if they appear as a field.
if _, ok := val.(json.Marshaler); ok {
// types which are e.g. structs, slices or maps and implement one of the following interfaces should not be
// marshalled by sheriff because they'll be correctly marshalled by json.Marshal instead.
// Otherwise (e.g. net.IP) a byte slice may be output as a list of uints instead of as an IP string.
switch val.(type) {
case json.Marshaler, encoding.TextMarshaler, fmt.Stringer:
return val, nil
}
k := v.Kind()
Expand Down
28 changes: 28 additions & 0 deletions sheriff_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package sheriff

import (
"encoding/json"
"net"
"testing"
"time"

Expand Down Expand Up @@ -498,3 +499,30 @@ func TestMarshal_InlineStruct(t *testing.T) {

assert.Equal(t, string(expected), string(actual))
}

type TestInet struct {
IPv4 net.IP `json:"ipv4"`
IPv6 net.IP `json:"ipv6"`
}

func TestMarshal_Inet(t *testing.T) {
v := TestInet{
IPv4: net.ParseIP("0.0.0.0").To4(),
IPv6: net.ParseIP("::").To16(),
}
o := &Options{}

actualMap, err := Marshal(o, v)
assert.NoError(t, err)

actual, err := json.Marshal(actualMap)
assert.NoError(t, err)

expected, err := json.Marshal(map[string]interface{}{
"ipv4": net.ParseIP("0.0.0.0").To4(),
"ipv6": net.ParseIP("::").To16(),
})
assert.NoError(t, err)

assert.Equal(t, string(expected), string(actual))
}

0 comments on commit 0ae0e1f

Please sign in to comment.