/
config.go
105 lines (84 loc) · 1.96 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package types
import (
"bytes"
"os"
"strings"
"text/template"
"github.com/pkg/errors"
"github.com/spf13/viper"
"github.com/sentinel-official/dvpn-node/utils"
)
var (
ct = strings.TrimSpace(`
# Name of the network interface
interface = "{{ .Interface }}"
# Port number to accept the incoming connections
listen_port = {{ .ListenPort }}
# Server private key
private_key = "{{ .PrivateKey }}"
`)
t = func() *template.Template {
t, err := template.New("wireguard_toml").Parse(ct)
if err != nil {
panic(err)
}
return t
}()
)
type Config struct {
Interface string `json:"interface" mapstructure:"interface"`
ListenPort uint16 `json:"listen_port" mapstructure:"listen_port"`
PrivateKey string `json:"private_key" mapstructure:"private_key"`
}
func NewConfig() *Config {
return &Config{}
}
func (c *Config) Validate() error {
if c.Interface == "" {
return errors.New("interface cannot be empty")
}
if c.ListenPort == 0 {
return errors.New("listen_port cannot be zero")
}
if c.PrivateKey == "" {
return errors.New("private_key cannot be empty")
}
if _, err := KeyFromString(c.PrivateKey); err != nil {
return errors.Wrap(err, "invalid private_key")
}
return nil
}
func (c *Config) WithDefaultValues() *Config {
key, err := NewPrivateKey()
if err != nil {
panic(err)
}
c.Interface = "wg0"
c.ListenPort = utils.RandomPort()
c.PrivateKey = key.String()
return c
}
func (c *Config) SaveToPath(path string) error {
var buffer bytes.Buffer
if err := t.Execute(&buffer, c); err != nil {
return err
}
return os.WriteFile(path, buffer.Bytes(), 0644)
}
func (c *Config) String() string {
var buffer bytes.Buffer
if err := t.Execute(&buffer, c); err != nil {
panic(err)
}
return buffer.String()
}
func ReadInConfig(v *viper.Viper) (*Config, error) {
config := NewConfig().WithDefaultValues()
if err := v.ReadInConfig(); err != nil {
return nil, err
}
if err := v.Unmarshal(config); err != nil {
return nil, err
}
return config, nil
}