From ed6bb75ce93fb33b13ffa48782147a2c7fd95628 Mon Sep 17 00:00:00 2001 From: Murad Biashimov Date: Thu, 14 Sep 2023 09:19:53 +0200 Subject: [PATCH] fix: panics on nil pointer --- sheriff.go | 2 +- sheriff_test.go | 7 +++++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/sheriff.go b/sheriff.go index 8ce11db..fb12667 100644 --- a/sheriff.go +++ b/sheriff.go @@ -56,7 +56,7 @@ 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() { + if !v.IsValid() || v.Kind() == reflect.Ptr && v.IsNil() { return data, nil } t := v.Type() diff --git a/sheriff_test.go b/sheriff_test.go index d079e4b..1cf5b66 100644 --- a/sheriff_test.go +++ b/sheriff_test.go @@ -747,3 +747,10 @@ func TestMarshal_NilSlice(t *testing.T) { assert.Equal(t, expect, string(jsonResult)) } + +func TestMarshal_NilPointer(t *testing.T) { + var a *AModel + v, err := Marshal(&Options{}, a) + assert.Nil(t, v) + assert.NoError(t, err) +}