-
Notifications
You must be signed in to change notification settings - Fork 56
/
archiveTar.go
117 lines (100 loc) · 1.94 KB
/
archiveTar.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
106
107
108
109
110
111
112
113
114
115
116
117
package serverHandler
import (
"archive/tar"
"compress/gzip"
"io"
"net/http"
"os"
)
func writeTar(tw *tar.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()
}
header := &tar.Header{
Name: archivePath,
Mode: 0664,
Size: size,
ModTime: fInfo.ModTime(),
AccessTime: fInfo.ModTime(),
ChangeTime: fInfo.ModTime(),
}
err := tw.WriteHeader(header)
if err != nil {
return err
}
if size == 0 || f == nil || fInfo.IsDir() {
return nil
}
_, err = io.Copy(tw, f)
if err != nil {
return err
}
return nil
}
func (h *handler) tar(w http.ResponseWriter, r *http.Request, pageData *responseData) {
if !pageData.CanArchive {
w.WriteHeader(http.StatusBadRequest)
return
}
selections, ok := h.normalizeArchiveSelections(r)
if !ok {
return
}
tw := tar.NewWriter(w)
defer func() {
err := tw.Close()
h.errHandler.LogError(err)
}()
h.archive(
w,
r,
pageData,
selections,
".tar",
"application/octet-stream",
func(f *os.File, fInfo os.FileInfo, relPath string) error {
return writeTar(tw, f, fInfo, relPath)
},
)
}
func (h *handler) tgz(w http.ResponseWriter, r *http.Request, pageData *responseData) {
if !pageData.CanArchive {
w.WriteHeader(http.StatusBadRequest)
return
}
selections, ok := h.normalizeArchiveSelections(r)
if !ok {
return
}
gzw, err := gzip.NewWriterLevel(w, gzip.BestSpeed)
if h.errHandler.LogError(err) {
return
}
defer func() {
err := gzw.Close()
h.errHandler.LogError(err)
}()
tw := tar.NewWriter(gzw)
defer func() {
err := tw.Close()
h.errHandler.LogError(err)
}()
h.archive(
w,
r,
pageData,
selections,
".tar.gz",
"application/octet-stream",
func(f *os.File, fInfo os.FileInfo, relPath string) error {
return writeTar(tw, f, fInfo, relPath)
},
)
}