From 805b2d490481d348856fb652473e73b25daf5aa2 Mon Sep 17 00:00:00 2001 From: Dmitry Kutakov Date: Mon, 4 Mar 2019 06:37:46 +0300 Subject: [PATCH] add support time.Duration on mapping (#1794) --- binding/binding_test.go | 17 +++++++++++++++++ binding/form_mapping.go | 13 +++++++++++++ 2 files changed, 30 insertions(+) diff --git a/binding/binding_test.go b/binding/binding_test.go index 16ca2027..5ae87957 100644 --- a/binding/binding_test.go +++ b/binding/binding_test.go @@ -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) +} diff --git a/binding/form_mapping.go b/binding/form_mapping.go index 1109e4d0..91fadcfd 100644 --- a/binding/form_mapping.go +++ b/binding/form_mapping.go @@ -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) @@ -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 {