fix bug that tag form:",default=1" are not effective in some cases, e.g: http://host/list?page_no=&page_size=

This commit is contained in:
Jerry 2020-05-06 10:25:23 +08:00
parent 235898e642
commit 9883d05806
2 changed files with 15 additions and 5 deletions

View File

@ -163,8 +163,10 @@ func setByForm(value reflect.Value, field reflect.StructField, form map[string][
val = opt.defaultValue val = opt.defaultValue
} }
if len(vs) > 0 { if len(vs) > 0 && vs[0] != "" {
val = vs[0] val = vs[0]
} else {
val = opt.defaultValue
} }
return true, setWithProperType(val, value, field) return true, setWithProperType(val, value, field)
} }

View File

@ -62,14 +62,22 @@ func TestMappingBaseTypes(t *testing.T) {
func TestMappingDefault(t *testing.T) { func TestMappingDefault(t *testing.T) {
var s struct { var s struct {
Int int `form:",default=9"` Int int `form:",default=9"`
Slice []int `form:",default=9"` PageNo int `form:"page_no,default=9"`
Array [1]int `form:",default=9"` String string `form:"string,default=9"`
Slice []int `form:",default=9"`
Array [1]int `form:",default=9"`
} }
err := mappingByPtr(&s, formSource{}, "form") form := map[string][]string{
"page_no": []string{""},
"string": []string{""},
}
err := mappingByPtr(&s, formSource(form), "form")
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, 9, s.Int) assert.Equal(t, 9, s.Int)
assert.Equal(t, 9, s.PageNo)
assert.Equal(t, "9", s.String)
assert.Equal(t, []int{9}, s.Slice) assert.Equal(t, []int{9}, s.Slice)
assert.Equal(t, [1]int{9}, s.Array) assert.Equal(t, [1]int{9}, s.Array)
} }