mirror of
https://git.freecumextremist.com/grumbulon/pomme.git
synced 2024-12-03 18:59:01 +00:00
65 lines
1.5 KiB
Go
65 lines
1.5 KiB
Go
package api
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
|
|
"dns.froth.zone/pomme/internal"
|
|
)
|
|
|
|
var errEmptyFile = errors.New("will not save empty file to FS")
|
|
|
|
// makeLocal takes a type path and then saves a zone file to either tmp or a permanent location.
|
|
func makeLocal(zone *ZoneRequest) error {
|
|
if _, err := os.Stat(fmt.Sprintf(zone.FileName, zone.User)); !os.IsNotExist(err) {
|
|
return fmt.Errorf("file %s already exists: %w", zone.FileName, err)
|
|
}
|
|
|
|
if len(zone.Body) == 0 {
|
|
return errEmptyFile
|
|
}
|
|
|
|
c, err := internal.ReadConfig()
|
|
if err != nil {
|
|
logger := newResponder(Response[any]{
|
|
Message: "no config file defined",
|
|
Err: err.Error(),
|
|
})
|
|
logger.writeLogEntry()
|
|
|
|
return fmt.Errorf("unable to parse directory: %w", err)
|
|
}
|
|
|
|
path := fmt.Sprintf("%s/%s/", c.ZoneDir, zone.FileName)
|
|
if err = os.MkdirAll(path, 0o750); err != nil {
|
|
logger := newResponder(Response[any]{
|
|
Message: "unable to make directory for zone files",
|
|
Err: err.Error(),
|
|
})
|
|
logger.writeLogEntry()
|
|
|
|
return fmt.Errorf("unable to make zone directory: %w", err)
|
|
}
|
|
|
|
f, err := os.Create(filepath.Clean(path + zone.FileName)) //nolint: gosec
|
|
if err != nil {
|
|
return fmt.Errorf("failed to write file locally: %w", err)
|
|
}
|
|
|
|
// close and remove the temporary file at the end of the program
|
|
defer func() {
|
|
if err = f.Close(); err != nil {
|
|
return
|
|
}
|
|
}()
|
|
|
|
err = os.WriteFile(f.Name(), zone.Body, 0o600)
|
|
|
|
if err != nil {
|
|
return fmt.Errorf("failed to write file locally: %w", err)
|
|
}
|
|
|
|
return nil
|
|
}
|