-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathzip.go
51 lines (40 loc) · 885 Bytes
/
zip.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
package utee
import (
"archive/zip"
"io"
"os"
"path/filepath"
"strings"
)
// Zip compress file or directory into writer
// pathToZip: the path to zip, could be a file or a directory
// dest: the writer to write zip content
func Zip(pathToZip string, dest io.Writer) error {
// create zip writer
zipWriter := zip.NewWriter(dest)
fn := func(filePath string, info os.FileInfo, err error) error {
if info.IsDir() {
return nil
}
if err != nil {
return err
}
// relative path
relPath := strings.TrimPrefix(filePath, filepath.Dir(pathToZip))
zipFile, err := zipWriter.Create(relPath)
if err != nil {
return err
}
fsFile, err := os.Open(filePath)
if err != nil {
return err
}
_, err = io.Copy(zipFile, fsFile)
return err
}
if err := filepath.Walk(pathToZip, fn); err != nil {
return err
}
err := zipWriter.Close()
return err
}