-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathzip.go
47 lines (45 loc) · 846 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
package main
import (
zipper "archive/zip"
"io"
"log"
"os"
"path/filepath"
)
func zip(w io.Writer, path string) error {
basePath := path
addFile := func(w *zipper.Writer, path string, stat os.FileInfo) error {
if stat.IsDir() {
return nil
}
file, err := os.Open(path)
if err != nil {
return err
}
defer file.Close()
path, err = filepath.Rel(basePath, path)
if err != nil {
return err
}
zw, err := w.Create(path)
if err != nil {
return err
}
if _, err := io.Copy(zw, file); err != nil {
return err
}
return w.Flush()
}
wZip := zipper.NewWriter(w)
defer func() {
if err := wZip.Close(); err != nil {
log.Println(err)
}
}()
return filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
return addFile(wZip, path, info)
})
}