-
Notifications
You must be signed in to change notification settings - Fork 55
/
archiveZip.go
68 lines (57 loc) · 1.06 KB
/
archiveZip.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
package serverHandler
import (
"archive/zip"
"io"
"net/http"
"os"
)
func writeZip(zw *zip.Writer, f *os.File, fInfo os.FileInfo, archivePath string) error {
if archivePath[0] == '/' {
archivePath = archivePath[1:]
}
if fInfo.IsDir() {
archivePath += "/"
}
var size int64
if !fInfo.IsDir() {
size = fInfo.Size()
}
w, err := zw.Create(archivePath)
if err != nil {
return err
}
if size == 0 || f == nil || fInfo.IsDir() {
return nil
}
_, err = io.Copy(w, f)
if err != nil {
return err
}
return nil
}
func (h *aliasHandler) zip(w http.ResponseWriter, r *http.Request, pageData *responseData) {
if !pageData.CanArchive {
w.WriteHeader(http.StatusBadRequest)
return
}
selections, ok := h.normalizeArchiveSelections(r)
if !ok {
return
}
zipWriter := zip.NewWriter(w)
defer func() {
err := zipWriter.Close()
h.logError(err)
}()
h.archive(
w,
r,
pageData,
selections,
".zip",
"application/zip",
func(f *os.File, fInfo os.FileInfo, relPath string) error {
return writeZip(zipWriter, f, fInfo, relPath)
},
)
}