-
Notifications
You must be signed in to change notification settings - Fork 0
/
extract.go
72 lines (58 loc) · 1.27 KB
/
extract.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
package zip_in_memory
import (
"archive/zip"
"bytes"
"io/ioutil"
)
type EmptyZipFileError struct {}
func (e *EmptyZipFileError) Error() string {
return "empty zip file"
}
func ExtractFirstFile(data []byte) ([]byte, error){
readerAt := bytes.NewReader(data)
zipReader, err := zip.NewReader(readerAt, int64(len(data)))
if err != nil {
return nil, err
}
if len(zipReader.File) > 0 {
file, err := zipReader.File[0].Open()
if err != nil {
return nil, err
}
extractedData, err := ioutil.ReadAll(file)
if err != nil {
return nil, err
}
if err := file.Close(); err != nil {
return nil, err
}
return extractedData, nil
}
return nil, &EmptyZipFileError{}
}
func ExtractFiles(data []byte) ([][]byte, error){
readerAt := bytes.NewReader(data)
zipReader, err := zip.NewReader(readerAt, int64(len(data)))
if err != nil {
return nil, err
}
files := make([][]byte, 0, len(zipReader.File))
for _, f := range zipReader.File {
file, err := f.Open()
if err != nil {
return nil, err
}
extractedData, err := ioutil.ReadAll(file)
if err != nil {
return nil, err
}
if err := file.Close(); err != nil {
return nil, err
}
files = append(files, extractedData)
}
if len(files) == 0 {
return nil, &EmptyZipFileError{}
}
return files, nil
}