Skip to content

Commit

Permalink
fix: handle invalid values in Decoder's decode method
Browse files Browse the repository at this point in the history
  • Loading branch information
wwqgtxx committed Dec 16, 2024
1 parent c786b72 commit 3f6823b
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
20 changes: 20 additions & 0 deletions common/structure/structure.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,27 @@ func (d *Decoder) Decode(src map[string]any, dst any) error {
return nil
}

// isNil returns true if the input is nil or a typed nil pointer.
func isNil(input any) bool {
if input == nil {
return true
}
val := reflect.ValueOf(input)
return val.Kind() == reflect.Pointer && val.IsNil()
}

func (d *Decoder) decode(name string, data any, val reflect.Value) error {
if isNil(data) {
// If the data is nil, then we don't set anything
// Maybe we should set to zero value?
return nil
}
if !reflect.ValueOf(data).IsValid() {
// If the input value is invalid, then we just set the value
// to be the zero value.
val.Set(reflect.Zero(val.Type()))
return nil
}
for {
kind := val.Kind()
if kind == reflect.Pointer && val.IsNil() {
Expand Down
18 changes: 18 additions & 0 deletions common/structure/structure_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -267,3 +267,21 @@ func TestStructure_TextUnmarshaller(t *testing.T) {
err = decoder.Decode(rawMap, s)
assert.NotNilf(t, err, "should throw error: %#v", s)
}

func TestStructure_Null(t *testing.T) {
rawMap := map[string]any{
"opt": map[string]any{
"bar": nil,
},
}

s := struct {
Opt struct {
Bar string `test:"bar,optional"`
} `test:"opt,optional"`
}{}

err := decoder.Decode(rawMap, &s)
assert.Nil(t, err)
assert.Equal(t, s.Opt.Bar, "")
}

0 comments on commit 3f6823b

Please sign in to comment.