hibiscus/export.go

75 lines
1.5 KiB
Go
Raw Normal View History

2024-03-23 15:36:01 +03:00
package main
import (
"archive/zip"
"io"
"log/slog"
"net/http"
"os"
"path/filepath"
)
var ExportPath = "data/export.zip"
// Export saves a .zip archive of the data folder to a file.
2024-03-23 15:36:01 +03:00
func Export(filename string) error {
file, err := os.Create(filename)
if err != nil {
slog.Error("error creating export archive", "error", err)
return err
}
w := zip.NewWriter(file)
walker := func(path string, info os.FileInfo, err error) error {
2024-03-26 14:00:32 +03:00
if path == filename || filepath.Ext(path) == ".zip" { //Ignore export file itself and .zip archives
2024-03-23 15:36:01 +03:00
return nil
}
slog.Debug("export crawling", "path", path)
if err != nil {
return err
}
if info.IsDir() {
return nil
}
file, err := os.Open(path)
if err != nil {
return err
}
f, err := w.Create(path)
if err != nil {
return err
}
_, err = io.Copy(f, file)
if err != nil {
return err
}
2024-05-04 21:36:43 +03:00
return file.Close()
2024-03-23 15:36:01 +03:00
}
err = filepath.Walk("data/", walker)
if err != nil {
slog.Error("error walking files", "error", err)
return err
}
2024-05-07 10:56:50 +03:00
err = w.Close()
2024-05-04 21:36:43 +03:00
if err != nil {
return err
}
2024-05-07 10:56:50 +03:00
return file.Close()
2024-03-23 15:36:01 +03:00
}
// GetExport returns a .zip archive with contents of the data folder.
// As a side effect, it creates the file in there.
2024-03-23 15:36:01 +03:00
func GetExport(w http.ResponseWriter, r *http.Request) {
err := Export(ExportPath)
if err != nil {
2024-05-04 21:36:43 +03:00
slog.Error("error getting export archive", "error", err)
2024-03-23 15:36:01 +03:00
http.Error(w, "could not export", http.StatusInternalServerError)
return
}
http.ServeFile(w, r, "data/export.zip")
}