isle/go/dnsmasq/tpl.go

66 lines
1.1 KiB
Go
Raw Normal View History

package dnsmasq
import (
"fmt"
"os"
"text/template"
)
// ConfDataHost describes a host which can be resolved by dnsmasq.
type ConfDataHost struct {
Name string
IP string
}
// ConfData describes all the data needed to populate a dnsmasq.conf file.
type ConfData struct {
Resolvers []string
Domain string
IP string
Hosts []ConfDataHost
}
var confTpl = template.Must(template.New("").Parse(`
port=53
bind-interfaces
listen-address={{ .IP }}
no-resolv
no-hosts
user=
group=
2022-11-05 15:25:24 +00:00
{{- $domain := .Domain -}}
{{- range .Hosts }}
address=/{{ .Name }}.hosts.{{ $domain }}/{{ .IP }}
{{ end -}}
{{- range .Resolvers }}
server={{ . }}
{{ end -}}
`))
// WriteConfFile renders a dnsmasq.conf using the given data to a new
// file at the given path.
func WriteConfFile(path string, data ConfData) error {
file, err := os.OpenFile(
path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0640,
)
if err != nil {
return fmt.Errorf("creating file: %w", err)
}
defer file.Close()
if err := confTpl.Execute(file, data); err != nil {
return fmt.Errorf("rendering template to file: %w", err)
}
return nil
}