pomme/internal/api/fs.go
2023-05-28 01:36:23 -04:00

67 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
}
logger := newResponder()
c, err := internal.ReadConfig()
if err != nil {
logger.Response = Response{
Message: "no config file defined",
Err: err.Error(),
}
logger.newLogEntry().panicLogger(logger.Response)
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.Response = Response{
Message: "unable to make directory for zone files",
Err: err.Error(),
}
logger.newLogEntry().errorLogger(logger.Response)
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
}