fix: keep missing pointer fields nil in remapMapToStruct

This commit is contained in:
Can Stand 2026-02-23 15:34:10 +08:00
parent 588a20f463
commit 4d548a92e9
3 changed files with 28 additions and 8 deletions

View File

@ -168,17 +168,22 @@ func remapValue(inMapValue reflect.Value, outStructValue reflect.Value) {
fi := structTyp.Field(i)
key := strings.Split(fi.Tag.Get("json"), ",")[0]
structField := outStructValue.Field(i)
structFieldDeref := outStructValue.Field(i)
value := inMapValue.MapIndex(reflect.ValueOf(key))
if !value.IsValid() {
continue
}
if value.Kind() == reflect.Interface {
if value.IsNil() {
continue
}
value = value.Elem()
}
structFieldDeref := structField
if structField.Type().Kind() == reflect.Pointer {
structField.Set(reflect.New(structField.Type().Elem()))
structFieldDeref = structField.Elem()
}
for _, e := range inMapValue.MapKeys() {
if key == e.String() {
value := inMapValue.MapIndex(e)
remapValue(value.Elem(), structFieldDeref)
}
}
remapValue(value, structFieldDeref)
}
default:
panic(inMapValue.Interface())

View File

@ -113,6 +113,21 @@ func TestRemapMapToStruct(t *testing.T) {
require.Equal(t, ourStruct.V1, "foobar")
}
func TestRemapMapToStructShouldKeepNilPointerForMissingField(t *testing.T) {
ourStruct := struct {
V1 string `json:"v1"`
PartitionKey *string `json:"partitionKey"`
}{}
inMap := map[string]any{
"v1": "foobar",
}
remapMapToStruct(inMap, &ourStruct)
require.Equal(t, "foobar", ourStruct.V1)
require.Nil(t, ourStruct.PartitionKey)
}
func TestConvertSelectOptionSet(t *testing.T) {
testCases := []struct {
name string

View File

@ -187,7 +187,7 @@ func TestBrowserContextAddCookies(t *testing.T) {
HttpOnly: false,
Secure: false,
SameSite: sameSite,
PartitionKey: playwright.String(""),
PartitionKey: nil,
},
}, cookies)