Skip to content

Commit c67c7aa

Browse files
authored
Merge pull request #5 from ieee0824/fix-duration
time.ParseDuration使う
2 parents 8f1e0ab + 1f5397f commit c67c7aa

File tree

2 files changed

+3
-84
lines changed

2 files changed

+3
-84
lines changed

duration.go

+3-62
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,10 @@
11
package getenv
22

33
import (
4-
"regexp"
54
"time"
6-
"strconv"
75
"os"
86
)
97

10-
var (
11-
reAlp = regexp.MustCompile(`[a-zA-Z]+`)
12-
reNum = regexp.MustCompile(`[0-9]+`)
13-
)
14-
158
func Duration(key string, def ...interface{}) time.Duration {
169
var d time.Duration
1710
if len(def) != 0 {
@@ -20,69 +13,17 @@ func Duration(key string, def ...interface{}) time.Duration {
2013
} else if dr, ok := def[0].(time.Duration); ok {
2114
d = dr
2215
} else if s, ok := def[0].(string); ok {
23-
d = parseDuration(s)
16+
d, _ = time.ParseDuration(s)
2417
}
2518
}
2619

2720
v := os.Getenv(key)
2821
if v == "" {
2922
return d
3023
}
31-
return parseDuration(v)
32-
}
24+
d, _ = time.ParseDuration(v)
3325

34-
func trimArray(a []string) []string {
35-
ret := []string{}
36-
37-
for _, e := range a {
38-
if len(e) != 0 {
39-
ret = append(ret, e)
40-
}
41-
}
42-
return ret
26+
return d
4327
}
4428

45-
func parseDuration(s string) time.Duration {
46-
alp := reAlp.Copy()
47-
num := reNum.Copy()
48-
49-
numNodes := trimArray(alp.Split(s, -1))
50-
alpNodes := trimArray(num.Split(s, -1))
51-
52-
if len(alpNodes) == 0 {
53-
if len(numNodes) == 0 {
54-
return 0
55-
}
56-
57-
s, err := strconv.Atoi(numNodes[0])
58-
if err != nil {
59-
return 0
60-
}
61-
return time.Duration(int64(s)) * time.Second
62-
}
63-
64-
if len(alpNodes) != len(numNodes) {
65-
return 0
66-
}
67-
68-
var ret time.Duration
69-
for i, n := range numNodes {
70-
t, err := strconv.Atoi(n)
71-
if err != nil {
72-
return 0
73-
}
74-
d := time.Duration(int64(t))
75-
switch alpNodes[i] {
76-
case "h":
77-
ret += d * time.Hour
78-
case "m":
79-
ret += d * time.Minute
80-
case "s":
81-
ret += d * time.Second
82-
default:
83-
return 0
84-
}
85-
}
86-
return ret
87-
}
8829

duration_test.go

-22
Original file line numberDiff line numberDiff line change
@@ -6,28 +6,6 @@ import (
66
"os"
77
)
88

9-
func TestParseDuration(t *testing.T) {
10-
tests := []struct {
11-
input string
12-
want time.Duration
13-
}{
14-
{"1h0m0s", 1*time.Hour},
15-
{"1h30m20s", 1*time.Hour + 30*time.Minute + 20*time.Second},
16-
{"60", 60*time.Second},
17-
{"", 0},
18-
{"a", 0},
19-
{"00af00", 0},
20-
{"0h30m", 30*time.Minute},
21-
{"20s", 20*time.Second},
22-
}
23-
24-
for _, test := range tests {
25-
if test.want != parseDuration(test.input) {
26-
t.Fatalf("want %v, but %v:", test.want, parseDuration(test.input))
27-
}
28-
}
29-
}
30-
319
func TestDuration(t *testing.T) {
3210
tests := []struct {
3311
input string

0 commit comments

Comments
 (0)