0
0
mirror of https://github.com/vx3r/wg-gen-web.git synced 2024-11-04 17:31:17 +00:00
wg-gen-web/util/tpl.go

91 lines
1.9 KiB
Go
Raw Normal View History

2020-01-30 06:45:49 +00:00
package util
import (
"bytes"
"gitlab.127-0-0-1.fr/vx3r/wg-gen-web/model"
"strings"
"text/template"
)
var (
clientTpl = `
[Interface]
Address = {{.Client.Address}}
PrivateKey = {{.Client.PrivateKey}}
DNS = {{.Server.Dns}}
[Peer]
PublicKey = {{.Server.PublicKey}}
PresharedKey = {{.Server.PresharedKey}}
AllowedIPs = {{.Client.AllowedIPs}}
Endpoint = {{.Server.Endpoint}}
PersistentKeepalive = {{.Server.PersistentKeepalive}}`
wgTpl = `
# {{.Server.Name}} / Updated: {{.Server.Updated}} / Created: {{.Server.Created}}
[Interface]
{{range .ServerAdresses}}
Address = {{.}}
{{end}}
ListenPort = {{.Server.ListenPort}}
PrivateKey = {{.Server.PrivateKey}}
{{$server := .Server}}
{{range .Clients}}
{{if .Enable}}
# {{.Name}} / {{.Email}} / Updated: {{.Updated}} / Created: {{.Created}}
[Peer]
PublicKey = {{.PublicKey}}
PresharedKey = {{$server.PresharedKey}}
AllowedIPs = {{.Address}}
{{end}}
{{end}}`
)
2020-01-30 07:17:29 +00:00
// DumpClient dump client wg config with go template
2020-01-30 06:45:49 +00:00
func DumpClient(client *model.Client, server *model.Server) (bytes.Buffer, error) {
var tplBuff bytes.Buffer
t, err := template.New("client").Parse(clientTpl)
if err != nil {
return tplBuff, err
}
return dump(t, struct {
Client *model.Client
Server *model.Server
}{
Client: client,
Server: server,
})
}
2020-01-30 07:17:29 +00:00
// DumpServerWg dump server wg config with go template
2020-01-30 06:45:49 +00:00
func DumpServerWg(clients []*model.Client, server *model.Server) (bytes.Buffer, error) {
var tplBuff bytes.Buffer
t, err := template.New("server").Parse(wgTpl)
if err != nil {
return tplBuff, err
}
return dump(t, struct {
2020-01-30 07:12:26 +00:00
Clients []*model.Client
Server *model.Server
2020-01-30 06:45:49 +00:00
ServerAdresses []string
}{
ServerAdresses: strings.Split(server.Address, ","),
2020-01-30 07:12:26 +00:00
Clients: clients,
Server: server,
2020-01-30 06:45:49 +00:00
})
}
2020-01-30 07:12:26 +00:00
func dump(tpl *template.Template, data interface{}) (bytes.Buffer, error) {
2020-01-30 06:45:49 +00:00
var tplBuff bytes.Buffer
err := tpl.Execute(&tplBuff, data)
if err != nil {
return tplBuff, err
}
return tplBuff, nil
}