-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcommon.go
104 lines (81 loc) · 1.53 KB
/
common.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
96
97
98
99
100
101
102
103
104
package textract
import (
"archive/zip"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"strings"
)
type DocumentParser interface {
extension() string
trueType() string
readFile(string) error
retrieveTextFromFile() (string, error)
}
type Filter func(string) bool
type MemberFileContent struct {
Identifier string
Data []byte
}
func ExtractArchiveContent(path string, filter Filter) (*[]MemberFileContent, error) {
ar, err := zip.OpenReader(path)
if err != nil {
return nil, err
}
defer ar.Close()
var list []MemberFileContent
for _, f := range ar.File {
if filter != nil {
if !(filter)(f.Name) {
continue
}
}
mf, err := f.Open()
if err != nil {
return nil, err
}
buf, err := io.ReadAll(mf)
if err != nil {
return nil, err
}
mfc := &MemberFileContent{
Identifier: f.Name,
Data: buf,
}
list = append(list, *mfc)
mf.Close()
}
return &list, nil
}
func GetTrueFileType(fp string) (string, error) {
f, err := os.Open(fp)
if err != nil {
return "", err
}
defer f.Close()
buf := make([]byte, 512)
_, err = f.Read(buf)
if err != nil {
return "", err
}
return http.DetectContentType(buf), nil
}
func GetFileExtension(filename string) string {
return strings.ToLower(filepath.Ext(filename))
}
func FatalExit(msg string) {
fmt.Fprintln(os.Stderr, msg)
os.Exit(1)
}
func Dump(path, content string) {
f, err := os.Create(path)
if err != nil {
FatalExit(err.Error())
}
defer f.Close()
if _, err = f.WriteString(content); err != nil {
FatalExit(err.Error())
}
}