-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathconfig_serde.go
More file actions
58 lines (51 loc) · 1.24 KB
/
config_serde.go
File metadata and controls
58 lines (51 loc) · 1.24 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 dasmon
import (
"encoding/json"
"fmt"
"time"
"gopkg.in/yaml.v3"
)
// DurationSer wraps time.DurationSer to provide JSON unmarshaling from strings
type DurationSer time.Duration
// UnmarshalJSON parses a duration string from JSON
func (d *DurationSer) UnmarshalJSON(b []byte) error {
var v interface{}
if err := json.Unmarshal(b, &v); err != nil {
return err
}
switch value := v.(type) {
case string:
parsed, err := time.ParseDuration(value)
if err != nil {
return err
}
*d = DurationSer(parsed)
return nil
case float64:
*d = DurationSer(time.Duration(value))
return nil
default:
return fmt.Errorf("invalid duration type")
}
}
// MarshalJSON converts duration to JSON string
func (d DurationSer) MarshalJSON() ([]byte, error) {
return json.Marshal(time.Duration(d).String())
}
// UnmarshalYAML parses a duration string from YAML
func (d *DurationSer) UnmarshalYAML(node *yaml.Node) error {
var s string
if err := node.Decode(&s); err != nil {
return err
}
parsed, err := time.ParseDuration(s)
if err != nil {
return err
}
*d = DurationSer(parsed)
return nil
}
// MarshalYAML converts duration to YAML string
func (d DurationSer) MarshalYAML() (interface{}, error) {
return time.Duration(d).String(), nil
}