forked from cloudflare/cloudflare-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
duration.go
40 lines (32 loc) · 838 Bytes
/
duration.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
package cloudflare
import (
"encoding/json"
"time"
)
// Duration implements json.Marshaler and json.Unmarshaler for time.Duration
// using the fmt.Stringer interface of time.Duration and time.ParseDuration.
type Duration struct {
time.Duration
}
// MarshalJSON encodes a Duration as a JSON string formatted using String.
func (d Duration) MarshalJSON() ([]byte, error) {
return json.Marshal(d.Duration.String())
}
// UnmarshalJSON decodes a Duration from a JSON string parsed using time.ParseDuration.
func (d *Duration) UnmarshalJSON(buf []byte) error {
var str string
err := json.Unmarshal(buf, &str)
if err != nil {
return err
}
dur, err := time.ParseDuration(str)
if err != nil {
return err
}
d.Duration = dur
return nil
}
var (
_ = json.Marshaler((*Duration)(nil))
_ = json.Unmarshaler((*Duration)(nil))
)