-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathduration.go
More file actions
58 lines (48 loc) · 1.28 KB
/
Copy pathduration.go
File metadata and controls
58 lines (48 loc) · 1.28 KB
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
package config
import (
"errors"
"fmt"
"time"
)
// Duration wraps a time.Duration with the ability to marshal and unmarshal to JSON the same as it
// marshals to text. For some reason time.Duration text marshaller uses "5s", but JSON uses
// nanoseconds as an integer. For configs we want environment and JSON configs to use the same
// values.
//
// The main disadvantages are that you must use NewDuration to create them from a time.Duration and
// you must add .Duration to use it as a time.Duration.
type Duration struct {
time.Duration
}
func NewDuration(d time.Duration) Duration {
return Duration{d}
}
func (v Duration) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf("\"%s\"", v.String())), nil
}
func (v *Duration) UnmarshalJSON(js []byte) error {
l := len(js)
if l < 2 {
return errors.New("Too short")
}
if js[0] != '"' || js[l-1] != '"' {
return errors.New("Too short")
}
duration, err := time.ParseDuration(string(js[1 : l-1]))
if err != nil {
return err
}
*v = NewDuration(duration)
return nil
}
func (v Duration) MarshalText() ([]byte, error) {
return []byte(v.String()), nil
}
func (v *Duration) UnmarshalText(text []byte) error {
duration, err := time.ParseDuration(string(text))
if err != nil {
return err
}
*v = NewDuration(duration)
return nil
}