-
Notifications
You must be signed in to change notification settings - Fork 1
/
config.go
75 lines (60 loc) · 1.29 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package wgconfig
import (
"io"
"gopkg.in/ini.v1"
)
type Config struct {
Interface Interface `json:"interface,omitempty"`
Peers Peers `json:"peers,omitempty"`
}
func (cfg *Config) AddPeer(p *Peer) {
cfg.Peers.Add(p)
}
func (cfg *Config) load(source interface{}) error {
opt := ini.LoadOptions{
SkipUnrecognizableLines: true,
AllowNonUniqueSections: true,
SpaceBeforeInlineComment: true,
}
f, err := ini.LoadSources(opt, source)
if err != nil {
return err
}
err = f.Section("Interface").MapTo(&cfg.Interface)
if err != nil {
return err
}
peers, err := f.SectionsByName("Peer")
if err != nil {
// No "Peer" sections is not an error. so just return here.
return nil
}
for _, p := range peers {
peer := Peer{}
err = p.MapTo(&peer)
if err != nil {
return err
}
peer.Comment = trimComment(p.Comment)
cfg.AddPeer(&peer)
}
return nil
}
func (cfg *Config) ReadFile(file string) error {
return cfg.load(file)
}
func (cfg *Config) Read(r io.Reader) error {
return cfg.load(r)
}
// Write config to file
func (cfg *Config) Write(w io.Writer) (int64, error) {
file := ini.Empty(ini.LoadOptions{
AllowNonUniqueSections: true,
IgnoreInlineComment: true,
})
err := file.ReflectFrom(&cfg)
if err != nil {
return -1, err
}
return file.WriteTo(w)
}