forked from zan8in/afrog
/
unzip.go
95 lines (79 loc) · 1.6 KB
/
unzip.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
94
95
package utils
import (
"archive/zip"
"fmt"
"io"
"os"
"path/filepath"
"strings"
)
// reference: https://raw.githubusercontent.com/artdarek/go-unzip/master/pkg/unzip/unzip.go
type Unzip struct {
}
func NewUnzip() *Unzip {
return &Unzip{}
}
func (uz Unzip) Extract(source, destination string) ([]string, error) {
r, err := zip.OpenReader(source)
if err != nil {
return nil, err
}
defer func() {
if err := r.Close(); err != nil {
panic(err)
}
}()
err = os.MkdirAll(destination, 0755)
if err != nil {
return nil, err
}
var extractedFiles []string
for _, f := range r.File {
err := uz.extractAndWriteFile(destination, f)
if err != nil {
return nil, err
}
extractedFiles = append(extractedFiles, f.Name)
}
return extractedFiles, nil
}
func (Unzip) extractAndWriteFile(destination string, f *zip.File) error {
rc, err := f.Open()
if err != nil {
return err
}
defer func() {
if err := rc.Close(); err != nil {
panic(err)
}
}()
path := filepath.Join(destination, f.Name)
if !strings.HasPrefix(path, filepath.Clean(destination)+string(os.PathSeparator)) {
return fmt.Errorf("%s: illegal file path", path)
}
if f.FileInfo().IsDir() {
err = os.MkdirAll(path, f.Mode())
if err != nil {
return err
}
} else {
err = os.MkdirAll(filepath.Dir(path), f.Mode())
if err != nil {
return err
}
f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode())
if err != nil {
return err
}
defer func() {
if err := f.Close(); err != nil {
panic(err)
}
}()
_, err = io.Copy(f, rc)
if err != nil {
return err
}
}
return nil
}