Skip to content

Commit

Permalink
use full match instead of strings.HasPrefix
Browse files Browse the repository at this point in the history
  • Loading branch information
efectn committed Sep 30, 2024
1 parent e2790a4 commit a381689
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
12 changes: 11 additions & 1 deletion decoder.go
Original file line number Diff line number Diff line change
Expand Up @@ -252,7 +252,17 @@ func isEmptyFields(fields []fieldWithPrefix, src map[string][]string) bool {
return false
}
for key := range src {
if !isEmpty(f.typ, src[key]) && strings.HasPrefix(key, path) {
nested := strings.IndexByte(key, '.') != -1

// for non required nested structs
c1 := strings.HasSuffix(f.prefix, ".") && key == path

// for required nested structs
c2 := f.prefix == "" && nested && strings.HasPrefix(key, path)

// for non nested fields
c3 := f.prefix == "" && !nested && key == path
if !isEmpty(f.typ, src[key]) && (c1 || c2 || c3) {
return false
}
}
Expand Down
17 changes: 17 additions & 0 deletions decoder_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1604,6 +1604,23 @@ func TestRequiredStructFiled(t *testing.T) {
}
}

type Node struct {
Value int `schema:"val,required"`
Next *Node `schema:"next,required"`
}

func TestRecursiveStruct(t *testing.T) {
v := map[string][]string{
"val": {"1"},
"next.val": {"2"},
}
var a Node
err := NewDecoder().Decode(&a, v)
if err != nil {
t.Errorf("error: %v", err)
}
}

func TestRequiredFieldIsMissingCorrectError(t *testing.T) {
type RM1S struct {
A string `schema:"rm1aa,required"`
Expand Down

0 comments on commit a381689

Please sign in to comment.