diff --git a/binding/binding_test.go b/binding/binding_test.go index 07619ebf..e03a59f5 100644 --- a/binding/binding_test.go +++ b/binding/binding_test.go @@ -1416,3 +1416,30 @@ func requestWithBody(method, path, body string) (req *http.Request) { req, _ = http.NewRequest(method, path, bytes.NewBufferString(body)) return } + +type bindTestData struct { + need interface{} + got interface{} + in map[string][]string +} + +func Test_Binding_BaseType(t *testing.T) { + type needFixDurationEmpty struct { + Duration time.Duration `form:"duration"` + } + + type needFixUnixNanoEmpty struct { + CreateTime time.Time `form:"createTime" time_format:"unixNano"` + } + + tests := []bindTestData{ + {need: &needFixDurationEmpty{}, got: &needFixDurationEmpty{}, in: http.Header{"duration": []string{}}}, + {need: &needFixUnixNanoEmpty{}, got: &needFixUnixNanoEmpty{}, in: http.Header{"createTime": []string{}}}, + } + + for _, v := range tests { + err := mapForm(v.got, v.in) + assert.NoError(t, err) + assert.Equal(t, v.need, v.got) + } +} diff --git a/binding/form_mapping.go b/binding/form_mapping.go index 1244b522..743cfdbc 100644 --- a/binding/form_mapping.go +++ b/binding/form_mapping.go @@ -404,6 +404,11 @@ func setTimeField(val string, structField reflect.StructField, value reflect.Val timeFormat = time.RFC3339 } + if val == "" { + value.Set(reflect.ValueOf(time.Time{})) + return nil + } + switch tf := strings.ToLower(timeFormat); tf { case "unix", "unixmilli", "unixmicro", "unixnano": tv, err := strconv.ParseInt(val, 10, 64) @@ -427,11 +432,6 @@ func setTimeField(val string, structField reflect.StructField, value reflect.Val return nil } - if val == "" { - value.Set(reflect.ValueOf(time.Time{})) - return nil - } - l := time.Local if isUTC, _ := strconv.ParseBool(structField.Tag.Get("time_utc")); isUTC { l = time.UTC @@ -475,6 +475,10 @@ func setSlice(vals []string, value reflect.Value, field reflect.StructField) err } func setTimeDuration(val string, value reflect.Value) error { + if val == "" { + val = "0" + } + d, err := time.ParseDuration(val) if err != nil { return err