forked from Rvn0xsy/zipcreater
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathzip.go
93 lines (82 loc) · 1.96 KB
/
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package main
import (
"archive/zip"
"io"
"log"
"os"
"path/filepath"
"strings"
)
// CreateZipFile ...
func CreateZipFile(DestFile string, SourceFile string, Path string) {
zipFile, err := os.OpenFile(DestFile, os.O_CREATE|os.O_RDWR, os.ModePerm)
if err != nil {
panic(err)
}
defer zipFile.Close()
archive := zip.NewWriter(zipFile)
defer archive.Close()
filepath.Walk(SourceFile, func(path string, info os.FileInfo, err error) error {
CheckErrorOnExit(err)
header, err := zip.FileInfoHeader(info)
CheckErrorOnExit(err)
header.Name = Path
header.Method = zip.Deflate
writer, err := archive.CreateHeader(header)
CheckErrorOnExit(err)
file, err := os.Open(path)
CheckErrorOnExit(err)
defer file.Close()
_, err = io.Copy(writer, file)
CheckErrorOnExit(err)
return err
})
}
// Zip ...
func Zip(srcFile string, destZip string, pathDest string, filename string) error {
zipfile, err := os.Create(destZip)
if err != nil {
return err
}
defer zipfile.Close()
archive := zip.NewWriter(zipfile)
defer archive.Close()
filepath.Walk(srcFile, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
header, err := zip.FileInfoHeader(info)
if err != nil {
return err
}
header.Name = strings.TrimPrefix(path, filepath.Dir(srcFile)+"/")
// header.Name = path
if strings.Contains(header.Name, filename) {
header.Name = strings.ReplaceAll(header.Name, filename, pathDest)
}
if strings.Contains(header.Name, "../") || strings.Contains(header.Name, "..\\") {
header.Method = zip.Deflate
} else {
if info.IsDir() {
header.Name += "/"
} else {
header.Method = zip.Deflate
}
}
log.Println("header.Name -> ", header.Name)
writer, err := archive.CreateHeader(header)
if err != nil {
return err
}
if !info.IsDir() {
file, err := os.Open(path)
if err != nil {
return err
}
defer file.Close()
_, err = io.Copy(writer, file)
}
return err
})
return err
}