diff options
Diffstat (limited to 'common')
-rw-r--r-- | common/types/convert.go | 20 | ||||
-rw-r--r-- | common/types/convert_test.go | 11 |
2 files changed, 31 insertions, 0 deletions
diff --git a/common/types/convert.go b/common/types/convert.go index 7beb3404e..0560eda0d 100644 --- a/common/types/convert.go +++ b/common/types/convert.go @@ -18,10 +18,30 @@ import ( "fmt" "html/template" "reflect" + "time" "github.com/spf13/cast" ) +// ToDuration converts v to time.Duration. +// See ToDurationE if you need to handle errors. +func ToDuration(v interface{}) time.Duration { + d, _ := ToDurationE(v) + return d +} + +// ToDurationE converts v to time.Duration. +func ToDurationE(v interface{}) (time.Duration, error) { + if n := cast.ToInt(v); n > 0 { + return time.Duration(n) * time.Millisecond, nil + } + d, err := time.ParseDuration(cast.ToString(v)) + if err != nil { + return 0, fmt.Errorf("cannot convert %v to time.Duration", v) + } + return d, nil +} + // ToStringSlicePreserveString is the same as ToStringSlicePreserveStringE, // but it never fails. func ToStringSlicePreserveString(v interface{}) []string { diff --git a/common/types/convert_test.go b/common/types/convert_test.go index 364228f41..88b303604 100644 --- a/common/types/convert_test.go +++ b/common/types/convert_test.go @@ -16,6 +16,7 @@ package types import ( "encoding/json" "testing" + "time" qt "github.com/frankban/quicktest" ) @@ -36,3 +37,13 @@ func TestToString(t *testing.T) { c.Assert(ToString([]byte("Hugo")), qt.Equals, "Hugo") c.Assert(ToString(json.RawMessage("Hugo")), qt.Equals, "Hugo") } + +func TestToDuration(t *testing.T) { + c := qt.New(t) + + c.Assert(ToDuration("200ms"), qt.Equals, 200*time.Millisecond) + c.Assert(ToDuration("200"), qt.Equals, 200*time.Millisecond) + c.Assert(ToDuration("4m"), qt.Equals, 4*time.Minute) + c.Assert(ToDuration("asdfadf"), qt.Equals, time.Duration(0)) + +} |