-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathzipfile.go
72 lines (63 loc) · 1.36 KB
/
zipfile.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
package dockerimagesave
// https://golangcode.com/create-zip-files-in-go/
import (
"archive/zip"
log "github.com/sirupsen/logrus"
"io"
"os"
)
// ZipFiles compresses one or many files into a single zip archive file
func ZipFiles(filename string, files []string) error {
filename = RemoveDoubleDots(filename)
newfile, err := os.Create(filename)
if err != nil {
return err
}
defer func(newfile *os.File) {
err := newfile.Close()
if err != nil {
log.Error(err)
}
}(newfile)
zipWriter := zip.NewWriter(newfile)
defer func(zipWriter *zip.Writer) {
err := zipWriter.Close()
if err != nil {
log.Error(err)
}
}(zipWriter)
// Add files to zip
for _, file := range files {
zipfile, err := os.Open(RemoveDoubleDots(file))
if err != nil {
return err
}
defer func(zipfile *os.File) {
err := zipfile.Close()
if err != nil {
log.Error(err)
}
}(zipfile)
// Get the file information
info, err := zipfile.Stat()
if err != nil {
return err
}
header, err := zip.FileInfoHeader(info)
if err != nil {
return err
}
// Change to deflate to gain better compression
// see http://golang.org/pkg/archive/zip/#pkg-constants
header.Method = zip.Deflate
writer, err := zipWriter.CreateHeader(header)
if err != nil {
return err
}
_, err = io.Copy(writer, zipfile)
if err != nil {
return err
}
}
return nil
}