forked from argoproj/argo-workflows
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathttl.go
59 lines (55 loc) · 1.37 KB
/
ttl.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package config
import (
"encoding/json"
"errors"
"strconv"
"strings"
"time"
)
// time.Duration forces you to specify in millis, and does not support days
// see https://stackoverflow.com/questions/48050945/how-to-unmarshal-json-into-durations
type TTL time.Duration
func (l TTL) MarshalJSON() ([]byte, error) {
return json.Marshal(time.Duration(l).String())
}
func (l *TTL) UnmarshalJSON(b []byte) error {
var v interface{}
if err := json.Unmarshal(b, &v); err != nil {
return err
}
switch value := v.(type) {
case string:
if value == "" {
*l = 0
return nil
}
if strings.HasSuffix(value, "d") {
days, err := strconv.Atoi(strings.TrimSuffix(value, "d"))
*l = TTL(time.Duration(days) * 24 * time.Hour)
return err
}
if strings.HasSuffix(value, "h") {
hours, err := strconv.Atoi(strings.TrimSuffix(value, "h"))
*l = TTL(time.Duration(hours) * time.Hour)
return err
}
if strings.HasSuffix(value, "m") {
minutes, err := strconv.Atoi(strings.TrimSuffix(value, "m"))
*l = TTL(time.Duration(minutes) * time.Minute)
return err
}
if strings.HasSuffix(value, "s") {
seconds, err := strconv.Atoi(strings.TrimSuffix(value, "s"))
*l = TTL(time.Duration(seconds) * time.Second)
return err
}
d, err := time.ParseDuration(value)
if err != nil {
return err
}
*l = TTL(d)
return nil
default:
return errors.New("invalid TTL")
}
}