From 5d047c6bc66b8e144c5c82f15c952f114626463b Mon Sep 17 00:00:00 2001 From: Ilya Baturin Date: Mon, 18 Jun 2018 05:19:26 +0300 Subject: [PATCH] fixes issue with slice of nil pointers (#144) fixes panic in case of marshaling of slice of nils like `[]*{nil, nil}` --- response.go | 8 ++++++-- response_test.go | 30 ++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/response.go b/response.go index f6a1b86..e8e85fa 100644 --- a/response.go +++ b/response.go @@ -207,9 +207,13 @@ func visitModelNode(model interface{}, included *map[string]*Node, node := new(Node) var er error + value := reflect.ValueOf(model) + if value.IsNil() { + return nil, nil + } - modelValue := reflect.ValueOf(model).Elem() - modelType := reflect.ValueOf(model).Type().Elem() + modelValue := value.Elem() + modelType := value.Type().Elem() for i := 0; i < modelValue.NumField(); i++ { structField := modelValue.Type().Field(i) diff --git a/response_test.go b/response_test.go index 157f434..dc89c48 100644 --- a/response_test.go +++ b/response_test.go @@ -37,6 +37,36 @@ func TestMarshalPayload(t *testing.T) { } } +func TestMarshalPayloadWithNulls(t *testing.T) { + + books := []*Book{nil, {ID:101}, nil} + var jsonData map[string]interface{} + + + out := bytes.NewBuffer(nil) + if err := MarshalPayload(out, books); err != nil { + t.Fatal(err) + } + + if err := json.Unmarshal(out.Bytes(), &jsonData); err != nil { + t.Fatal(err) + } + raw, ok := jsonData["data"] + if !ok { + t.Fatalf("data key does not exist") + } + arr, ok := raw.([]interface{}) + if !ok { + t.Fatalf("data is not an Array") + } + for i := 0; i < len(arr); i++ { + if books[i] == nil && arr[i] != nil || + books[i] != nil && arr[i] == nil { + t.Fatalf("restored data is not equal to source") + } + } +} + func TestMarshal_attrStringSlice(t *testing.T) { tags := []string{"fiction", "sale"} b := &Book{ID: 1, Tags: tags}