gestion-dns/dnsconfig/toml_zones.go

81 lines
1.4 KiB
Go

package dnsconfig
import (
"fmt"
"os"
"strings"
"github.com/BurntSushi/toml"
)
type TomlVariables struct {
Name string `toml:"name"`
Type string `toml:"type"`
Value string `toml:"value"`
}
type TomlRecord struct {
Name string `toml:"name"`
Type string `toml:"type"`
Value string `toml:"value"`
TTL int `toml:"ttl"`
}
type TomlZone struct {
Domain string `toml:"domain"`
DefaultTTL int `toml:"default_ttl"`
TomlRecords []TomlRecord `toml:"record"`
TomlVariables []TomlVariables `toml:"variable"`
}
func GetTomlZones() ([]TomlZone, error) {
var zones []TomlZone
files, err := os.ReadDir("./zones/")
if err != nil {
return zones, err
}
for _, file := range files {
name := file.Name()
path := fmt.Sprintf("./zones/%s", name)
if !strings.HasSuffix(strings.ToLower(name), ".toml") {
continue
}
var zone TomlZone
_, err = toml.DecodeFile(path, &zone)
if err != nil {
continue
}
if len(zone.Domain) == 0 {
continue
}
if zone.DefaultTTL <= 0 {
zone.DefaultTTL = 3600
}
zones = append(zones, zone)
}
return zones, nil
}
func CreateTomlZone(zone TomlZone) error {
if len(zone.Domain) == 0 {
return fmt.Errorf("zone name cannot be empty")
}
name := strings.ReplaceAll(strings.ToLower(zone.Domain), ".", "_")
path := fmt.Sprintf("./zones/%s.toml", name)
file, err := os.Create(path)
if err != nil {
return err
}
return toml.NewEncoder(file).Encode(&zone)
}