pomme/internal/api/fs.go
Sam Therapy f0fdd15473
use new import URL
Signed-off-by: Sam Therapy <sam@samtherapy.net>
2023-02-17 19:42:48 +01:00

57 lines
1.4 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 {
logHandler(genericResponseFields{"error": err.Error(), "message": "no config file defined"})
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 {
logHandler(genericResponseFields{"error": err.Error(), "message": "unable to make directory for zone files"})
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
}