wireguard: Config.WriteTo()

Signed-off-by: Alejandro Mery <amery@jpi.io>
This commit is contained in:
2023-08-25 17:59:59 +00:00
parent 202f2e6dfc
commit 2e716da23f
+33 -4
View File
@@ -1,17 +1,35 @@
package wireguard package wireguard
import ( import (
"bytes"
"errors" "errors"
"fmt" "fmt"
"io" "io"
"net/netip" "net/netip"
"strconv" "strconv"
"strings" "strings"
"text/template"
"darvaza.org/core" "darvaza.org/core"
"gopkg.in/gcfg.v1" "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 // Config represents a wgN.conf file
type Config struct { type Config struct {
Interface InterfaceConfig Interface InterfaceConfig
@@ -19,13 +37,24 @@ type Config struct {
} }
// GetAddress is a shortcut to the interface's address // GetAddress is a shortcut to the interface's address
func (f *Config) GetAddress() netip.Addr { func (wg *Config) GetAddress() netip.Addr {
return f.Interface.Address return wg.Interface.Address
} }
// Peers tells how many peers are described // Peers tells how many peers are described
func (f *Config) Peers() int { func (wg *Config) Peers() int {
return len(f.Peer) 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 // InterfaceConfig represents the [Interface] section