diff --git a/duration.go b/duration.go index 9c332ff..1b8ef04 100644 --- a/duration.go +++ b/duration.go @@ -1,17 +1,10 @@ package getenv import ( - "regexp" "time" - "strconv" "os" ) -var ( - reAlp = regexp.MustCompile(`[a-zA-Z]+`) - reNum = regexp.MustCompile(`[0-9]+`) -) - func Duration(key string, def ...interface{}) time.Duration { var d time.Duration if len(def) != 0 { @@ -20,7 +13,7 @@ func Duration(key string, def ...interface{}) time.Duration { } else if dr, ok := def[0].(time.Duration); ok { d = dr } else if s, ok := def[0].(string); ok { - d = parseDuration(s) + d, _ = time.ParseDuration(s) } } @@ -28,61 +21,9 @@ func Duration(key string, def ...interface{}) time.Duration { if v == "" { return d } - return parseDuration(v) -} + d, _ = time.ParseDuration(v) -func trimArray(a []string) []string { - ret := []string{} - - for _, e := range a { - if len(e) != 0 { - ret = append(ret, e) - } - } - return ret + return d } -func parseDuration(s string) time.Duration { - alp := reAlp.Copy() - num := reNum.Copy() - - numNodes := trimArray(alp.Split(s, -1)) - alpNodes := trimArray(num.Split(s, -1)) - - if len(alpNodes) == 0 { - if len(numNodes) == 0 { - return 0 - } - - s, err := strconv.Atoi(numNodes[0]) - if err != nil { - return 0 - } - return time.Duration(int64(s)) * time.Second - } - - if len(alpNodes) != len(numNodes) { - return 0 - } - - var ret time.Duration - for i, n := range numNodes { - t, err := strconv.Atoi(n) - if err != nil { - return 0 - } - d := time.Duration(int64(t)) - switch alpNodes[i] { - case "h": - ret += d * time.Hour - case "m": - ret += d * time.Minute - case "s": - ret += d * time.Second - default: - return 0 - } - } - return ret -} diff --git a/duration_test.go b/duration_test.go index 7bc3847..df81c60 100644 --- a/duration_test.go +++ b/duration_test.go @@ -6,28 +6,6 @@ import ( "os" ) -func TestParseDuration(t *testing.T) { - tests := []struct { - input string - want time.Duration - }{ - {"1h0m0s", 1*time.Hour}, - {"1h30m20s", 1*time.Hour + 30*time.Minute + 20*time.Second}, - {"60", 60*time.Second}, - {"", 0}, - {"a", 0}, - {"00af00", 0}, - {"0h30m", 30*time.Minute}, - {"20s", 20*time.Second}, - } - - for _, test := range tests { - if test.want != parseDuration(test.input) { - t.Fatalf("want %v, but %v:", test.want, parseDuration(test.input)) - } - } -} - func TestDuration(t *testing.T) { tests := []struct { input string