1
1
package getenv
2
2
3
3
import (
4
- "regexp"
5
4
"time"
6
- "strconv"
7
5
"os"
8
6
)
9
7
10
- var (
11
- reAlp = regexp .MustCompile (`[a-zA-Z]+` )
12
- reNum = regexp .MustCompile (`[0-9]+` )
13
- )
14
-
15
8
func Duration (key string , def ... interface {}) time.Duration {
16
9
var d time.Duration
17
10
if len (def ) != 0 {
@@ -20,69 +13,17 @@ func Duration(key string, def ...interface{}) time.Duration {
20
13
} else if dr , ok := def [0 ].(time.Duration ); ok {
21
14
d = dr
22
15
} else if s , ok := def [0 ].(string ); ok {
23
- d = parseDuration (s )
16
+ d , _ = time . ParseDuration (s )
24
17
}
25
18
}
26
19
27
20
v := os .Getenv (key )
28
21
if v == "" {
29
22
return d
30
23
}
31
- return parseDuration (v )
32
- }
24
+ d , _ = time .ParseDuration (v )
33
25
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
43
27
}
44
28
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
- }
88
29
0 commit comments