-
Notifications
You must be signed in to change notification settings - Fork 0
/
zip.go
68 lines (56 loc) · 1.22 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
package main
import (
"archive/zip"
"fmt"
"io"
"os"
"path/filepath"
"strings"
)
func unzipSource(source, destination string) error {
reader, err := zip.OpenReader(source)
if err != nil {
return err
}
defer reader.Close()
destination, err = filepath.Abs(destination)
if err != nil {
return err
}
for _, f := range reader.File {
err := unzipFile(f, destination)
if err != nil {
return err
}
}
return nil
}
func unzipFile(f *zip.File, destination string) error {
filePath := filepath.Join(destination, f.Name)
if !strings.HasPrefix(filePath, filepath.Clean(destination)+string(os.PathSeparator)) {
return fmt.Errorf("invalid file path: %s", filePath)
}
if f.FileInfo().IsDir() {
if err := os.MkdirAll(filePath, os.ModePerm); err != nil {
return err
}
return nil
}
if err := os.MkdirAll(filepath.Dir(filePath), os.ModePerm); err != nil {
return err
}
destinationFile, err := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode())
if err != nil {
return err
}
defer destinationFile.Close()
zippedFile, err := f.Open()
if err != nil {
return err
}
defer zippedFile.Close()
if _, err := io.Copy(destinationFile, zippedFile); err != nil {
return err
}
return nil
}