-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
56 lines (49 loc) · 1.26 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
package main
import (
"fmt"
"os"
"time"
"gopkg.in/yaml.v3"
)
// Config represents application configuration.
type Config struct {
ListenAddr string `yaml:"listen_addr"`
Timeout time.Duration `yaml:"timeout"`
Targets []Target `yaml:"targets"`
}
// Target is a single ConnectBox device.
type Target struct {
Addr string `yaml:"addr"`
Username string `yaml:"username"`
Password string `yaml:"password"`
}
// ReadConfig returns configuration populated from the config file.
func ReadConfig(file string) (Config, error) {
data, err := os.ReadFile(file) //nolint:gosec
if err != nil {
return Config{}, fmt.Errorf("read file: %w", err)
}
var conf Config
if err := yaml.Unmarshal(data, &conf); err != nil {
return Config{}, fmt.Errorf("unmarshal file: %w", err)
}
// Set defaults
if conf.ListenAddr == "" {
conf.ListenAddr = "0.0.0.0:9119"
}
if conf.Timeout == 0 {
conf.Timeout = 30 * time.Second
}
for i := range conf.Targets {
if conf.Targets[i].Addr == "" {
return Config{}, fmt.Errorf("found target with empty address")
}
if conf.Targets[i].Username == "" {
conf.Targets[i].Username = "NULL"
}
if conf.Targets[i].Password == "" {
return Config{}, fmt.Errorf("found target with empty password")
}
}
return conf, nil
}