mirror of
https://github.com/duke-git/lancet.git
synced 2026-11-16 05:12:11 +08:00
fix(maputil): validate MapToStruct inputs before reflection (#375)
This commit is contained in:
1 parent
b282ada39e
commit
18e9bc9cda
2 files changed
+24
No files matched your search
@@ -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() {
|
||||
|
||||
|
||||
Reference in new issue
Block a user