diff --git a/binding/form_mapping.go b/binding/form_mapping.go index 6982fd4f..86389289 100644 --- a/binding/form_mapping.go +++ b/binding/form_mapping.go @@ -306,6 +306,21 @@ func setByForm(value reflect.Value, field reflect.StructField, form map[string][ default: var val string if !ok || len(vs) == 0 || (len(vs) > 0 && vs[0] == "") { + // An empty value with no default is the same as no value for + // numeric and boolean fields. Reporting it as unset keeps a + // pointer field nil instead of pointing at a zero value, so + // callers can tell "age=" apart from "age=0". Plain fields + // are unaffected: they keep their zero value either way. + // time.Duration keeps its existing handling and is left out + // of this change. + if !opt.isDefaultExists && !isDuration(value) { + switch value.Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, + reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, + reflect.Float32, reflect.Float64, reflect.Bool: + return false, nil + } + } val = opt.defaultValue } else if len(vs) > 0 { val = vs[0] @@ -507,6 +522,10 @@ func setSlice(vals []string, value reflect.Value, field reflect.StructField, opt return nil } +func isDuration(value reflect.Value) bool { + return value.Type() == reflect.TypeOf(time.Duration(0)) +} + func setTimeDuration(val string, value reflect.Value) error { if val == "" { val = "0" diff --git a/binding/form_mapping_test.go b/binding/form_mapping_test.go index c78f7398..7511355c 100644 --- a/binding/form_mapping_test.go +++ b/binding/form_mapping_test.go @@ -173,6 +173,52 @@ func TestMappingFormWithEmptyToDefault(t *testing.T) { assert.Equal(t, "DefVal", s.F) } +func TestMappingEmptyValueLeavesPointerFieldsNil(t *testing.T) { + var s struct { + Age *int `form:"age"` + Count *uint `form:"count"` + Score *float64 `form:"score"` + Flag *bool `form:"flag"` + Name *string `form:"name"` + Plain int `form:"plain"` + } + err := mapForm(&s, map[string][]string{ + "age": {""}, + "count": {""}, + "score": {""}, + "flag": {""}, + "name": {""}, + "plain": {""}, + }) + require.NoError(t, err) + assert.Nil(t, s.Age) + assert.Nil(t, s.Count) + assert.Nil(t, s.Score) + assert.Nil(t, s.Flag) + // Strings keep their previous behavior: a present but empty value + // still produces a pointer to "". + require.NotNil(t, s.Name) + assert.Equal(t, "", *s.Name) + assert.Equal(t, 0, s.Plain) +} + +func TestMappingPointerFieldZeroValueStaysSet(t *testing.T) { + var s struct { + Age *int `form:"age"` + } + err := mapForm(&s, map[string][]string{"age": {"0"}}) + require.NoError(t, err) + require.NotNil(t, s.Age) + assert.Equal(t, 0, *s.Age) + + var missing struct { + Age *int `form:"age"` + } + err = mapForm(&missing, map[string][]string{}) + require.NoError(t, err) + assert.Nil(t, missing.Age) +} + func TestMapFormWithTag(t *testing.T) { var s struct { F int `externalTag:"field"`