wireguard: Config.WriteTo()
Signed-off-by: Alejandro Mery <amery@jpi.io>
This commit is contained in:
@@ -1,17 +1,40 @@
|
|||||||
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{
|
||||||
|
"PrefixJoin": func(a []netip.Prefix, sep string) string {
|
||||||
|
s := make([]string, len(a))
|
||||||
|
for i, p := range a {
|
||||||
|
s[i] = p.String()
|
||||||
|
}
|
||||||
|
return strings.Join(s, sep)
|
||||||
|
},
|
||||||
|
}).Parse(`[Interface]
|
||||||
|
Address = {{.Interface.Address}}
|
||||||
|
PrivateKey = {{.Interface.PrivateKey}}
|
||||||
|
ListenPort = {{.Interface.ListenPort}}
|
||||||
|
{{- range .Peer }}
|
||||||
|
|
||||||
|
[Peer]
|
||||||
|
PublicKey = {{.PublicKey}}
|
||||||
|
Endpoint = {{.Endpoint}}
|
||||||
|
AllowedIPs = {{ PrefixJoin .AllowedIPs ", "}}
|
||||||
|
{{- end }}
|
||||||
|
`))
|
||||||
|
|
||||||
// Config represents a wgN.conf file
|
// Config represents a wgN.conf file
|
||||||
type Config struct {
|
type Config struct {
|
||||||
Interface InterfaceConfig
|
Interface InterfaceConfig
|
||||||
@@ -28,6 +51,17 @@ func (f *Config) Peers() int {
|
|||||||
return len(f.Peer)
|
return len(f.Peer)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WriteTo writes a Wireguard [Config] onto the provided [io.Writer]
|
||||||
|
func (f *Config) WriteTo(w io.Writer) (int64, error) {
|
||||||
|
var buf bytes.Buffer
|
||||||
|
|
||||||
|
if err := configTemplate.Execute(&buf, f); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return buf.WriteTo(w)
|
||||||
|
}
|
||||||
|
|
||||||
// InterfaceConfig represents the [Interface] section
|
// InterfaceConfig represents the [Interface] section
|
||||||
type InterfaceConfig struct {
|
type InterfaceConfig struct {
|
||||||
Address netip.Addr
|
Address netip.Addr
|
||||||
|
|||||||
Reference in New Issue
Block a user