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
|
package upload
import (
"archive/tar"
"compress/gzip"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"time"
)
// Backup creates an archive of a project's uploads and writes it
// to the response as a download
func Backup(res http.ResponseWriter) error {
ts := time.Now().Unix()
filename := fmt.Sprintf("uploads-%d.bak.tar.gz", ts)
tmp := os.TempDir()
// create uploads-{stamp}.bak.tar.gz
f, err := os.Create(filepath.Join(tmp, filename))
if err != nil {
return err
}
defer f.Close()
// loop through directory and gzip files
// add all to uploads.bak.tar.gz tarball
gz := gzip.NewWriter(f)
tarball := tar.NewWriter(gz)
err = filepath.Walk("uploads", func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
h := &tar.Header{
Name: info.Name(),
Size: info.Size(),
Mode: int64(info.Mode()),
ModTime: info.ModTime(),
}
err = tarball.WriteHeader(h)
if err != nil {
return err
}
src, err := os.Open(path)
if err != nil {
return err
}
_, err = io.Copy(tarball, src)
return err
})
// write data to response
data, err := os.Open(filepath.Join(tmp, filename))
if err != nil {
return err
}
defer data.Close()
disposition := `attachment; filename=%s`
info, err := data.Stat()
if err != nil {
return err
}
res.Header().Set("Content-Type", "application/octet-stream")
res.Header().Set("Content-Disposition", fmt.Sprintf(disposition, ts))
res.Header().Set("Content-Length", fmt.Sprintf("%d", info.Size()))
_, err = io.Copy(res, data)
return err
}
|