diff --git a/binding/binding_test.go b/binding/binding_test.go index f0b6f795..a789412c 100644 --- a/binding/binding_test.go +++ b/binding/binding_test.go @@ -1271,3 +1271,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 d6199c4f..972a56e8 100644 --- a/binding/form_mapping.go +++ b/binding/form_mapping.go @@ -267,6 +267,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", "unixnano": tv, err := strconv.ParseInt(val, 10, 0) @@ -285,11 +290,6 @@ func setTimeField(val string, structField reflect.StructField, value reflect.Val } - 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 @@ -333,6 +333,10 @@ func setSlice(vals []string, value reflect.Value, field reflect.StructField) err } func setTimeDuration(val string, value reflect.Value, field reflect.StructField) error { + if val == "" { + val = "0" + } + d, err := time.ParseDuration(val) if err != nil { return err