-
-
Notifications
You must be signed in to change notification settings - Fork 90
/
duration.go
54 lines (44 loc) · 1.02 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
package ecspresso
import (
"encoding/json"
"fmt"
"time"
"github.com/goccy/go-yaml"
)
type Duration struct {
time.Duration
}
func (d *Duration) UnmarshalJSON(b []byte) error {
return d.unmarshal(b, json.Unmarshal)
}
func (d *Duration) MarshalJSON() ([]byte, error) {
return d.marshal()
}
func (d *Duration) UnmarshalYAML(b []byte) error {
return d.unmarshal(b, yaml.Unmarshal)
}
func (d *Duration) MarshalYAML() ([]byte, error) {
return d.marshal()
}
func (d *Duration) unmarshal(b []byte, unmarshaler func([]byte, interface{}) error) error {
var unmarshalled interface{}
err := unmarshaler(b, &unmarshalled)
if err != nil {
return err
}
switch value := unmarshalled.(type) {
case string:
d.Duration, err = time.ParseDuration(value)
if err != nil {
return err
}
case float64:
d.Duration = time.Duration(value)
default:
return fmt.Errorf("invalid duration format: %v", value)
}
return nil
}
func (d *Duration) marshal() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, d.Duration.String())), nil
}