From 18e9bc9cdadd1b2438093ebb608e03f5c9d75829 Mon Sep 17 00:00:00 2001 From: Yusuf Efe <120668197+yuefdev@users.noreply.github.com> Date: Fri, 23 Oct 2026 13:10:00 +0300 Subject: [PATCH] fix(maputil): validate MapToStruct inputs before reflection (#375) --- maputil/map.go | 7 +++++++ maputil/map_test.go | 17 +++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/maputil/map.go b/maputil/map.go index 3823805..9cd19c8 100644 --- a/maputil/map.go +++ b/maputil/map.go @@ -318,6 +318,10 @@ func HasKey[K comparable, V any](m map[K]V, key K) bool { // MapToStruct converts map to struct // Play: https://go.dev/play/p/7wYyVfX38Dp func MapToStruct(m map[string]any, structObj any) error { + target := reflect.ValueOf(structObj) + if target.Kind() != reflect.Ptr || target.IsNil() || target.Elem().Kind() != reflect.Struct { + return fmt.Errorf("destination must be a non-nil pointer to a struct") + } for k, v := range m { err := setStructField(structObj, k, v) if err != nil { @@ -347,6 +351,9 @@ func setStructField(structObj any, fieldName string, fieldValue any) error { } val := reflect.ValueOf(fieldValue) + if !val.IsValid() { + return fmt.Errorf("Map value type don't match struct field type") + } if fieldVal.Type() != val.Type() { diff --git a/maputil/map_test.go b/maputil/map_test.go index 4a2512e..436cdae 100644 --- a/maputil/map_test.go +++ b/maputil/map_test.go @@ -11,6 +11,23 @@ import ( "github.com/duke-git/lancet/v2/internal" ) +func TestMapToStructInvalidInputs(t *testing.T) { + var nilTarget *struct { + Name string `json:"name"` + } + for _, dst := range []any{nil, nilTarget, 1, &[]int{}} { + if err := MapToStruct(map[string]any{"name": "value"}, dst); err == nil { + t.Errorf("expected an error for %T", dst) + } + } + var dst struct { + Name string `json:"name"` + } + if err := MapToStruct(map[string]any{"name": nil}, &dst); err == nil { + t.Error("expected an error for an incompatible nil value") + } +} + func TestKeys(t *testing.T) { t.Parallel()