-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
zipfile.go
56 lines (47 loc) · 1.06 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
package dockerimagesave
// https://golangcode.com/create-zip-files-in-go/
import (
"archive/zip"
"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 newfile.Close()
zipWriter := zip.NewWriter(newfile)
defer zipWriter.Close()
// Add files to zip
for _, file := range files {
zipfile, err := os.Open(RemoveDoubleDots(file))
if err != nil {
return err
}
defer zipfile.Close()
// 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
}