-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathzip.go
More file actions
51 lines (45 loc) · 875 Bytes
/
zip.go
File metadata and controls
51 lines (45 loc) · 875 Bytes
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 main
import (
"archive/zip"
"io"
"os"
"path/filepath"
"github.com/astaxie/beego/logs"
)
func walkFunc(w *zip.Writer, basePath, 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()
}
func FileZip(w io.Writer, path string) error {
basePath := path
wZip := zip.NewWriter(w)
defer func() {
if err := wZip.Close(); err != nil {
logs.Error(err.Error())
}
}()
return filepath.Walk(basePath, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
return walkFunc(wZip, basePath, path, info)
})
}