Skip to content

Commit

Permalink
Write tar.gz when requesting to download a directory
Browse files Browse the repository at this point in the history
  • Loading branch information
zer0tonin committed Nov 13, 2023
1 parent 4d7bc58 commit 866940f
Show file tree
Hide file tree
Showing 2 changed files with 79 additions and 2 deletions.
9 changes: 8 additions & 1 deletion backend/browser/handlers.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package browser

import (
"fmt"
"io"
"log"
"net/http"
Expand All @@ -13,7 +14,8 @@ import (
// GET /stream
// StreamFile streams the content of the requested file
func StreamFile(c *gin.Context) {
pathInDataDir := getAbsolutePath(c.Param("path"))
path := c.Param("path")
pathInDataDir := getAbsolutePath(path)

dir, err := isDir(pathInDataDir)
if err != nil {
Expand All @@ -24,6 +26,11 @@ func StreamFile(c *gin.Context) {
}

if dir {
c.Header(
"Content-Disposition",
fmt.Sprintf("attachment; filename=%s.tar.gz", path[1:len(path)-1]),
)
writeTarGz(pathInDataDir, c.Writer)
} else {
c.File(pathInDataDir)
}
Expand Down
72 changes: 71 additions & 1 deletion backend/browser/utils.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package browser

import (
"archive/tar"
"compress/gzip"
"io"
"io/fs"
"os"
"path/filepath"
Expand Down Expand Up @@ -76,6 +79,73 @@ func isDir(filepath string) (bool, error) {
return fileInfo.IsDir(), nil
}

func sendTarGz() error {
func writeTarGz(filepath string, w io.Writer) error {
gzipWriter := gzip.NewWriter(w)
defer gzipWriter.Close()
tarWriter := tar.NewWriter(gzipWriter)
defer tarWriter.Close()

writeDirectoryToTarGz(filepath, tarWriter, filepath)

return nil
}

func writeDirectoryToTarGz(directory string, tarWriter *tar.Writer, subPath string) error {
files, err := os.ReadDir(directory)
if err != nil {
return err
}

for _, file := range files {
currentPath := filepath.Join(directory, file.Name())
if file.IsDir() {
err := writeDirectoryToTarGz(currentPath, tarWriter, subPath)
if err != nil {
return err
}
} else {
fileInfo, err := file.Info()
if err != nil {
return err
}
err = writeFileToTarGz(currentPath, tarWriter, fileInfo, subPath)
if err != nil {
return err
}
}
}

return nil
}

func writeFileToTarGz(path string, tarWriter *tar.Writer, fileInfo os.FileInfo, subPath string) error {
file, err := os.Open(path)
if err != nil {
return err
}
defer file.Close()

path, err = filepath.EvalSymlinks(path)
if err != nil {
return err
}

subPath, err = filepath.EvalSymlinks(subPath)
if err != nil {
return err
}

header, err := tar.FileInfoHeader(fileInfo, path)
if err != nil {
return err
}
header.Name = path[len(subPath):]

err = tarWriter.WriteHeader(header)
if err != nil {
return err
}

_, err = io.Copy(tarWriter, file)
return err
}

0 comments on commit 866940f

Please sign in to comment.