-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathzipstream.go
105 lines (89 loc) · 1.9 KB
/
zipstream.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package main
import (
"compress/flate"
"errors"
"fmt"
"github.com/mholt/archiver"
"net/http"
"os"
"path"
"path/filepath"
)
type PathWalkerArgs struct {
filePath string
info os.FileInfo
err error
z archiver.Zip
dirPath string
dirPathInfo os.FileInfo
}
// Add discovered file to zip
func pathWalker(args PathWalkerArgs) error {
if args.err != nil {
return args.err
}
internalName, err := archiver.NameInArchive(args.dirPathInfo, args.dirPath, args.filePath)
if err != nil {
return err
}
file, err := os.Open(args.filePath)
if err != nil {
return err
}
err = args.z.Write(archiver.File{
FileInfo: archiver.FileInfo{
FileInfo: args.info,
CustomName: internalName,
},
ReadCloser: file,
})
if err != nil {
return err
}
err = file.Close()
if err != nil {
return err
}
return nil
}
// Create streamed zip file of a job
func ZipDir(dirName string, root string, reqW http.ResponseWriter, _ *http.Request) error {
dirPath := path.Join(root, dirName)
dirPathInfo, err := os.Stat(dirPath)
if err != nil {
return errors.New("reading job dir")
}
z := archiver.Zip{
CompressionLevel: flate.NoCompression,
MkdirAll: true,
SelectiveCompression: true,
ContinueOnError: false,
OverwriteExisting: false,
ImplicitTopLevelFolder: false,
}
err = z.Create(reqW)
if err != nil {
return errors.New("creating zip file")
}
defer func() {
_ = z.Close()
}()
reqW.Header().Set(
"Content-Disposition",
fmt.Sprintf("attachment; filename=%s.zip", dirName),
)
err = filepath.Walk(dirPath, func(path string, info os.FileInfo, err error) error {
return pathWalker(PathWalkerArgs{
filePath: path,
info: info,
err: err,
z: z,
dirPath: dirPath,
dirPathInfo: dirPathInfo,
})
})
if err != nil {
return errors.New("reading job directory")
}
return nil
}