Skip to content
This repository has been archived by the owner on Jul 22, 2024. It is now read-only.

Commit

Permalink
string to time duration hook
Browse files Browse the repository at this point in the history
  • Loading branch information
mitchellh committed May 18, 2015
1 parent 51d99d1 commit d7ecef0
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
20 changes: 20 additions & 0 deletions decode_hooks.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"reflect"
"strconv"
"strings"
"time"
)

// typedDecodeHook takes a raw DecodeHookFunc (an interface{}) and turns
Expand Down Expand Up @@ -98,6 +99,25 @@ func StringToSliceHookFunc(sep string) DecodeHookFunc {
}
}

// StringToTimeDurationHookFunc returns a DecodeHookFunc that converts
// strings to time.Duration.
func StringToTimeDurationHookFunc() DecodeHookFunc {
return func(
f reflect.Type,
t reflect.Type,
data interface{}) (interface{}, error) {
if f.Kind() != reflect.String {
return data, nil
}
if t != reflect.TypeOf(time.Duration(5)) {
return data, nil
}

// Convert it by parsing
return time.ParseDuration(data.(string))
}
}

func WeaklyTypedHook(
f reflect.Kind,
t reflect.Kind,
Expand Down
30 changes: 30 additions & 0 deletions decode_hooks_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"errors"
"reflect"
"testing"
"time"
)

func TestComposeDecodeHookFunc(t *testing.T) {
Expand Down Expand Up @@ -123,6 +124,35 @@ func TestStringToSliceHookFunc(t *testing.T) {
}
}

func TestStringToTimeDurationHookFunc(t *testing.T) {
f := StringToTimeDurationHookFunc()

strType := reflect.TypeOf("")
timeType := reflect.TypeOf(time.Duration(5))
cases := []struct {
f, t reflect.Type
data interface{}
result interface{}
err bool
}{
{strType, timeType, "5s", 5 * time.Second, false},
{strType, timeType, "5", time.Duration(0), true},
{strType, strType, "5", "5", false},
}

for i, tc := range cases {
actual, err := DecodeHookExec(f, tc.f, tc.t, tc.data)
if tc.err != (err != nil) {
t.Fatalf("case %d: expected err %#v", i, tc.err)
}
if !reflect.DeepEqual(actual, tc.result) {
t.Fatalf(
"case %d: expected %#v, got %#v",
i, tc.result, actual)
}
}
}

func TestWeaklyTypedHook(t *testing.T) {
var f DecodeHookFunc = WeaklyTypedHook

Expand Down

0 comments on commit d7ecef0

Please sign in to comment.