Merge f2443d1877cbc6636c505bef73a7869ba1eb0836 into b2b489dbf4826c2c630717a77fd5e42774625410

This commit is contained in:
kim 2026-01-18 21:05:39 +08:00 committed by GitHub
commit be63befeb2
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 19 additions and 8 deletions

View File

@ -231,19 +231,24 @@ func setByForm(value reflect.Value, field reflect.StructField, form map[string][
switch value.Kind() {
case reflect.Slice:
if len(vs) == 0 {
if vs == nil {
if !opt.isDefaultExists {
return false, nil
}
vs = []string{opt.defaultValue}
// pre-process the default value for multi if present
cfTag := field.Tag.Get("collection_format")
if cfTag == "" || cfTag == "multi" {
vs = strings.Split(opt.defaultValue, ",")
} else {
vs = []string{opt.defaultValue}
}
}
if len(vs) == 0 {
return true, setSlice(vs, value, field)
}
if ok, err = trySetCustom(vs[0], value); ok {
return ok, err
}
@ -259,11 +264,12 @@ func setByForm(value reflect.Value, field reflect.StructField, form map[string][
return false, nil
}
vs = []string{opt.defaultValue}
// pre-process the default value for multi if present
cfTag := field.Tag.Get("collection_format")
if cfTag == "" || cfTag == "multi" {
vs = strings.Split(opt.defaultValue, ",")
} else {
vs = []string{opt.defaultValue}
}
}

View File

@ -689,7 +689,7 @@ func TestMappingEmptyValues(t *testing.T) {
// field present but empty
err = mappingByPtr(&s, formSource{"slice": {}}, "form")
require.NoError(t, err)
assert.Equal(t, []int{5}, s.Slice)
assert.Equal(t, []int{}, s.Slice)
// field present with values
err = mappingByPtr(&s, formSource{"slice": {"1", "2", "3"}}, "form")
@ -718,10 +718,15 @@ func TestMappingEmptyValues(t *testing.T) {
Slice []int `form:"slice"`
}
// field present but empty
err := mappingByPtr(&s, formSource{"slice": {}}, "form")
// field not present
err := mappingByPtr(&s, formSource{}, "form")
require.NoError(t, err)
assert.Equal(t, []int(nil), s.Slice)
// field present but empty
err = mappingByPtr(&s, formSource{"slice": {}}, "form")
require.NoError(t, err)
assert.Equal(t, []int{}, s.Slice)
})
t.Run("array without default", func(t *testing.T) {
@ -750,7 +755,7 @@ func TestMappingEmptyValues(t *testing.T) {
// field present but empty
err = mappingByPtr(&s, formSource{"slice_multi": {}, "slice_csv": {}}, "form")
require.NoError(t, err)
assert.Equal(t, []int{1, 2, 3}, s.SliceMulti)
assert.Equal(t, []int{1, 2, 3}, s.SliceCsv)
assert.Equal(t, []int{}, s.SliceMulti)
assert.Equal(t, []int{}, s.SliceCsv)
})
}