-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathzip-file-reader.go
85 lines (69 loc) · 1.61 KB
/
zip-file-reader.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
package main
import (
"archive/zip"
"bytes"
"fmt"
"io"
"net/http"
"strings"
)
type ZipFileReader struct {
data []byte
}
func (zipFileReader ZipFileReader) GetFileContentByExtention(extentions []string) (string, error) {
// Open the zip archive
zipReader, err := zip.NewReader(bytes.NewReader(zipFileReader.data), int64(len(zipFileReader.data)))
if err != nil {
return "", err
}
content := ""
for _, file := range zipReader.File {
if !hasSuffixes(file.Name, extentions...) {
continue
}
// Open the file from the zip archive
fileReader, err := file.Open()
if err != nil {
fmt.Println("Error opening file in zip:", err)
continue
}
defer fileReader.Close()
// Read the content of the file
fileContent, err := io.ReadAll(fileReader)
if err != nil {
fmt.Println("Error reading file in zip:", err)
continue
}
content += string(fileContent)
}
return content, nil
}
func NewZipFileReader(url string) (ZipFileReader, error) {
zipFileReader := ZipFileReader{}
// Download the zip file
resp, err := http.Get(url)
if err != nil {
fmt.Println("Error downloading zip file:", err)
return zipFileReader, err
}
defer resp.Body.Close()
// Read the content of the zip file into memory
zipData, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Println("Error reading zip file:", err)
return zipFileReader, err
}
zipFileReader.data = zipData
return zipFileReader, err
}
func hasSuffixes(str string, suffixes ...string) bool {
if len(suffixes) == 0 {
return true
}
for _, suffix := range suffixes {
if strings.HasSuffix(str, suffix) {
return true
}
}
return false
}