From c435f42cc837f55d86b1e52dadde69ffcc995a93 Mon Sep 17 00:00:00 2001 From: xuancanh Date: Thu, 1 Oct 2020 15:25:30 +0800 Subject: [PATCH] fix: Handle empty interface when marshalling (#26) Co-authored-by: Canh Nguyen --- sheriff.go | 3 +++ sheriff_test.go | 12 ++++++++++++ 2 files changed, 15 insertions(+) diff --git a/sheriff.go b/sheriff.go index 56e5922..91666b5 100644 --- a/sheriff.go +++ b/sheriff.go @@ -52,6 +52,9 @@ type Marshaller interface { // In all other cases we can't derive the type in a meaningful way and is therefore an `interface{}`. func Marshal(options *Options, data interface{}) (interface{}, error) { v := reflect.ValueOf(data) + if !v.IsValid() { + return data, nil + } t := v.Type() // Initialise nestedGroupsMap, diff --git a/sheriff_test.go b/sheriff_test.go index 3e0820d..cf63288 100644 --- a/sheriff_test.go +++ b/sheriff_test.go @@ -663,3 +663,15 @@ func TestMarshal_AliaString(t *testing.T) { _, err := Marshal(&Options{}, &v) assert.NoError(t, err) } + +type EmptyInterfaceStruct struct { + Data interface{} `json:"data"` +} + +func TestMarshal_EmptyInterface(t *testing.T) { + v := EmptyInterfaceStruct{} + o := &Options{} + + _, err := Marshal(o, v) + assert.NoError(t, err) +}