mirror of
https://git.freecumextremist.com/grumbulon/pomme.git
synced 2024-07-01 07:46:07 +00:00
74 lines
1.7 KiB
Go
74 lines
1.7 KiB
Go
package api
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
|
|
"git.freecumextremist.com/grumbulon/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(where path, zone *ZoneRequest) error {
|
|
var (
|
|
path string
|
|
file string
|
|
c *internal.Config
|
|
err 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([]byte(zone.Body)) == 0 {
|
|
return errEmptyFile
|
|
}
|
|
|
|
switch where {
|
|
case Tmp:
|
|
path = fmt.Sprintf("/tmp/tmpfile-%s-%s", zone.RawFileName, zone.User)
|
|
case Perm:
|
|
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.RawFileName)
|
|
|
|
file = zone.RawFileName
|
|
|
|
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 + file)) //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(), []byte(zone.Body), 0o600)
|
|
|
|
if err != nil {
|
|
return fmt.Errorf("failed to write file locally: %w", err)
|
|
}
|
|
|
|
return nil
|
|
}
|