-
Notifications
You must be signed in to change notification settings - Fork 0
/
archive.go
59 lines (50 loc) · 1.02 KB
/
archive.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
package main
import (
"archive/zip"
"io"
"os"
"path/filepath"
)
type ZipWorker struct {
zipWriter *zip.Writer
root string
}
func NewZipWorker(zipFile io.Writer, root string) *ZipWorker {
return &ZipWorker{
zipWriter: zip.NewWriter(zipFile),
root: root,
}
}
func (worker *ZipWorker) run() error {
defer worker.close()
return filepath.Walk(worker.root, worker.zipAllFiles)
}
func (worker *ZipWorker) zipAllFiles(path string, info os.FileInfo, err error) error {
if info.IsDir() {
return nil
}
fileWriter, err := worker.zipWriter.Create(path)
if err != nil {
return err
}
fileReader, err := os.Open(path)
if err != nil {
return err
}
_, err = io.Copy(fileWriter, fileReader)
return err
}
func (worker *ZipWorker) close() {
worker.zipWriter.Close()
}
func zipFolder(folder string, file string) error {
if _, err := os.Stat(file); err == nil {
os.Remove(file)
}
zipFile, err := os.Create(file)
if err != nil {
return err
}
defer zipFile.Close()
return NewZipWorker(zipFile, folder).run()
}