/
config.go
57 lines (46 loc) · 1.1 KB
/
config.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
package config
import (
"fmt"
"io"
"time"
yaml "gopkg.in/yaml.v2"
)
type duration time.Duration
type Config struct {
Targets []string `yaml:"targets"`
Ping struct {
Interval duration `yaml:"interval"`
Timeout duration `yaml:"timeout"`
History int `yaml:"history-size"`
Size uint16 `yaml:"payload-size"`
} `yaml:"ping"`
}
func (d *duration) UnmarshalYAML(unmashal func(interface{}) error) error {
var s string
if err := unmashal(&s); err != nil {
return err
}
dur, err := time.ParseDuration(s)
if err != nil {
return fmt.Errorf("failed to decode duration: %w", err)
}
*d = duration(dur)
return nil
}
// Duration is a convenience getter.
func (d duration) Duration() time.Duration {
return time.Duration(d)
}
// Set updates the underlying duration.
func (d *duration) Set(dur time.Duration) {
*d = duration(dur)
}
// FromYAML reads YAML from reader and unmarshals it to Config.
func FromYAML(r io.Reader) (*Config, error) {
c := &Config{}
err := yaml.NewDecoder(r).Decode(c)
if err != nil {
return nil, fmt.Errorf("failed to decode YAML: %w", err)
}
return c, nil
}