Skip to content

Commit

Permalink
ISSUE#31 Fixed panic on nil ptr
Browse files Browse the repository at this point in the history
  • Loading branch information
Thomas Lombard authored and mweibel committed Aug 30, 2021
1 parent 9291c3b commit bfb5dba
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
9 changes: 8 additions & 1 deletion sheriff.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import (
"reflect"
"strings"

version "github.com/hashicorp/go-version"
"github.com/hashicorp/go-version"
)

// Options determine which struct fields are being added to the output map.
Expand Down Expand Up @@ -217,6 +217,13 @@ func marshalValue(options *Options, v reflect.Value) (interface{}, error) {
}
k := v.Kind()

switch k {
case reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
if v.IsNil() {
return val, nil
}
}

if k == reflect.Ptr {
v = v.Elem()
val = v.Interface()
Expand Down
22 changes: 21 additions & 1 deletion sheriff_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import (
"testing"
"time"

version "github.com/hashicorp/go-version"
"github.com/hashicorp/go-version"
"github.com/stretchr/testify/assert"
)

Expand Down Expand Up @@ -713,3 +713,23 @@ func TestMarshal_EmptyInterface(t *testing.T) {
_, err := Marshal(o, v)
assert.NoError(t, err)
}

func TestMarshal_BooleanPtrMap(t *testing.T) {
tru := true

toMarshal := map[string]*bool{
"example": &tru,
"another": nil,
}

marshalMap, err := Marshal(&Options{}, toMarshal)
assert.NoError(t, err)

marshal, err := json.Marshal(marshalMap)
assert.NoError(t, err)

expect, err := json.Marshal(toMarshal)
assert.NoError(t, err)

assert.Equal(t, string(marshal), string(expect))
}

0 comments on commit bfb5dba

Please sign in to comment.