Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add support time.Duration on mapping #1794

Merged
merged 2 commits into from
Mar 4, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions binding/binding_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1413,3 +1413,20 @@ func TestBindingUnknownTypeChan(t *testing.T) {
assert.Error(t, err)
assert.Equal(t, errUnknownType, err)
}

func TestBindingTimeDuration(t *testing.T) {
var s struct {
Timeout time.Duration `form:"timeout"`
}

// ok
req := formPostRequest("", "timeout=5s")
err := Form.Bind(req, &s)
assert.NoError(t, err)
assert.Equal(t, 5*time.Second, s.Timeout)

// error
req = formPostRequest("", "timeout=wrong")
err = Form.Bind(req, &s)
assert.Error(t, err)
}
13 changes: 13 additions & 0 deletions binding/form_mapping.go
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,10 @@ func setWithProperType(val string, value reflect.Value, field reflect.StructFiel
case reflect.Int32:
return setIntField(val, 32, value)
case reflect.Int64:
switch value.Interface().(type) {
case time.Duration:
return setTimeDuration(val, value, field)
}
return setIntField(val, 64, value)
case reflect.Uint:
return setUintField(val, 0, value)
Expand Down Expand Up @@ -263,6 +267,15 @@ func setSlice(vals []string, value reflect.Value, field reflect.StructField) err
return nil
}

func setTimeDuration(val string, value reflect.Value, field reflect.StructField) error {
d, err := time.ParseDuration(val)
if err != nil {
return err
}
value.Set(reflect.ValueOf(d))
return nil
}

func head(str, sep string) (head string, tail string) {
idx := strings.Index(str, sep)
if idx < 0 {
Expand Down