forked from smallstep/certificates
-
Notifications
You must be signed in to change notification settings - Fork 0
/
duration.go
63 lines (56 loc) · 1.77 KB
/
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package provisioner
import (
"encoding/json"
"time"
"github.com/pkg/errors"
)
// Duration is a wrapper around Time.Duration to aid with marshal/unmarshal.
type Duration struct {
time.Duration
}
// NewDuration parses a duration string and returns a Duration type or an error
// if the given string is not a duration.
func NewDuration(s string) (*Duration, error) {
d, err := time.ParseDuration(s)
if err != nil {
return nil, errors.Wrapf(err, "error parsing %s as duration", s)
}
return &Duration{Duration: d}, nil
}
// MarshalJSON parses a duration string and sets it to the duration.
//
// A duration string is a possibly signed sequence of decimal numbers, each with
// optional fraction and a unit suffix, such as "300ms", "-1.5h" or "2h45m".
// Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".
func (d *Duration) MarshalJSON() ([]byte, error) {
return json.Marshal(d.Duration.String())
}
// UnmarshalJSON parses a duration string and sets it to the duration.
//
// A duration string is a possibly signed sequence of decimal numbers, each with
// optional fraction and a unit suffix, such as "300ms", "-1.5h" or "2h45m".
// Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".
func (d *Duration) UnmarshalJSON(data []byte) (err error) {
var (
s string
dd time.Duration
)
if d == nil {
return errors.New("duration cannot be nil")
}
if err = json.Unmarshal(data, &s); err != nil {
return errors.Wrapf(err, "error unmarshaling %s", data)
}
if dd, err = time.ParseDuration(s); err != nil {
return errors.Wrapf(err, "error parsing %s as duration", s)
}
d.Duration = dd
return
}
// Value returns 0 if the duration is null, the inner duration otherwise.
func (d *Duration) Value() time.Duration {
if d == nil {
return 0
}
return d.Duration
}