wireguard: Config.WriteTo()
Signed-off-by: Alejandro Mery <amery@jpi.io>
This commit is contained in:
+33
-4
@@ -1,17 +1,35 @@
|
||||
package wireguard
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/netip"
|
||||
"strconv"
|
||||
"strings"
|
||||
"text/template"
|
||||
|
||||
"darvaza.org/core"
|
||||
"gopkg.in/gcfg.v1"
|
||||
)
|
||||
|
||||
var configTemplate = template.Must(template.New("config").Funcs(template.FuncMap{
|
||||
"StringsJoin": strings.Join,
|
||||
}).Parse(`[Interface]
|
||||
Address = {{.Interface.Address}}
|
||||
PrivateKey = {{.Interface.PrivateKey}}
|
||||
ListenPort = {{.Interface.ListenPort}}
|
||||
{{range .Peer}}
|
||||
|
||||
[Peer]
|
||||
# {{.Endpoint.Name}}
|
||||
PublicKey = {{.PublicKey}}
|
||||
Endpoint = {{.Endpoint}}
|
||||
AllowedIPs = {{ StringsJoin .AllowedIPs ", "}}
|
||||
{{end}}
|
||||
`))
|
||||
|
||||
// Config represents a wgN.conf file
|
||||
type Config struct {
|
||||
Interface InterfaceConfig
|
||||
@@ -19,13 +37,24 @@ type Config struct {
|
||||
}
|
||||
|
||||
// GetAddress is a shortcut to the interface's address
|
||||
func (f *Config) GetAddress() netip.Addr {
|
||||
return f.Interface.Address
|
||||
func (wg *Config) GetAddress() netip.Addr {
|
||||
return wg.Interface.Address
|
||||
}
|
||||
|
||||
// Peers tells how many peers are described
|
||||
func (f *Config) Peers() int {
|
||||
return len(f.Peer)
|
||||
func (wg *Config) Peers() int {
|
||||
return len(wg.Peer)
|
||||
}
|
||||
|
||||
// WriteTo writes a Wireguard [Config] onto the provided [io.Writer]
|
||||
func (wg *Config) WriteTo(w io.Writer) (int64, error) {
|
||||
var buf bytes.Buffer
|
||||
|
||||
if err := configTemplate.Execute(&buf, wg); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
return buf.WriteTo(w)
|
||||
}
|
||||
|
||||
// InterfaceConfig represents the [Interface] section
|
||||
|
||||
Reference in New Issue
Block a user