-
Notifications
You must be signed in to change notification settings - Fork 13
/
file.go
147 lines (124 loc) · 2.37 KB
/
file.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
package helper
import (
"bytes"
"encoding/csv"
"io"
"io/ioutil"
"os"
"path"
"runtime"
"strings"
"github.com/juju/errors"
)
const (
png = "png"
jpeg = "jpeg"
)
var supportedFileExtensions = []string{
png, jpeg,
}
func GetFileExtensionFromBase64Header(base64Header string) (string, error) {
for _, ext := range supportedFileExtensions {
if strings.Contains(base64Header, ext) {
return "." + ext, nil
}
}
return "", errors.New("unsupported image type")
}
func ExistsInDir(filename, dir string) bool {
fileInfo, err := ioutil.ReadDir(dir)
if err != nil {
return false
}
for _, file := range fileInfo {
if filename == file.Name() {
return true
}
}
return false
}
func GetTemplateDirectory() string {
templateFolder, has := os.LookupEnv("APP_TEMPLATE_FOLDER")
var dir string
if has {
dir = templateFolder
} else {
_, filename, _, _ := runtime.Caller(0)
dir = path.Join(path.Dir(filename), "../../../templates")
}
return dir
}
func CSVToMap(reader *bytes.Buffer) ([]map[string]string, error) {
r := csv.NewReader(reader)
r.Comma = ';'
var rows []map[string]string
var header []string
for {
record, err := r.Read()
if err == io.EOF {
break
}
if err != nil {
return nil, err
}
if header == nil {
header = record
} else {
dict := map[string]string{}
for i := range header {
dict[header[i]] = record[i]
}
rows = append(rows, dict)
}
}
return rows, nil
}
func FileExistsInDir(filename, dir string) bool {
fileInfo, err := ioutil.ReadDir(dir)
if err != nil {
return false
}
for _, file := range fileInfo {
if filename == file.Name() {
return true
}
}
return false
}
func Copy(src, dst string, bufferSize int64) error {
sourceFileStat, err := os.Stat(src)
if err != nil {
return err
}
if !sourceFileStat.Mode().IsRegular() {
return errors.New(src + " is not a regular file.")
}
source, err := os.Open(src)
if err != nil {
return err
}
defer source.Close()
_, err = os.Stat(dst)
if err == nil {
return errors.Errorf("file %s already exists.", dst)
}
destination, err := os.Create(dst)
if err != nil {
return err
}
defer destination.Close()
buf := make([]byte, bufferSize)
for {
n, err := source.Read(buf)
if err != nil && err != io.EOF {
return err
}
if n == 0 {
break
}
if _, err := destination.Write(buf[:n]); err != nil {
return err
}
}
return err
}