-
Notifications
You must be signed in to change notification settings - Fork 3
/
time.go
55 lines (50 loc) · 1.12 KB
/
time.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
package jsontypes
import (
"encoding/json"
"strings"
"time"
)
// Duration wraps a time.Duration.
// It marshals / unmarshals to a string with the time.ParseDuration format.
type Duration struct {
time.Duration
}
// Or returns d.Duration if d is not nil, or ifAbsent if d is nil.
// Or only really works if Duration is used as a pointer
//
// type Config struct {
// TTL *Duration // pointer type
// }
//
// ttl := config.TTL.Or(15*time.Minute)
func (d *Duration) Or(ifAbsent time.Duration) time.Duration {
if d == nil {
return ifAbsent
}
return d.Duration
}
//goland:noinspection GoMixedReceiverTypes
func (d *Duration) UnmarshalJSON(raw []byte) error {
var str string
err := json.Unmarshal(raw, &str)
if err != nil {
return err
}
parsed, err := time.ParseDuration(str)
if err != nil {
return err
}
d.Duration = parsed
return nil
}
//goland:noinspection GoMixedReceiverTypes
func (d Duration) MarshalJSON() ([]byte, error) {
str := d.String()
if strings.HasSuffix(str, "m0s") {
str = str[:len(str)-2]
}
if strings.Contains(str, "h0m") {
str = strings.Replace(str, "h0m", "h", 1)
}
return json.Marshal(str)
}