From a38168951d4b42fdd8e5997e7da9a337c8462b41 Mon Sep 17 00:00:00 2001 From: Muhammed Efe Cetin Date: Mon, 30 Sep 2024 22:25:53 +0300 Subject: [PATCH] use full match instead of strings.HasPrefix via: https://github.com/gorilla/schema/pull/178 --- decoder.go | 12 +++++++++++- decoder_test.go | 17 +++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/decoder.go b/decoder.go index a6a4aa0..4523a83 100644 --- a/decoder.go +++ b/decoder.go @@ -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 } } diff --git a/decoder_test.go b/decoder_test.go index d9d662c..33edfc6 100644 --- a/decoder_test.go +++ b/decoder_test.go @@ -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"`