-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelpers.go
88 lines (76 loc) · 1.92 KB
/
helpers.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
package owo
import (
"fmt"
"io"
"math"
"os"
"bytes"
)
// FilesToNamedReaders Converts a list of file names to named readers.
func FilesToNamedReaders(names []string) (files []NamedReader, err error) {
if len(names) > FileCountLimit {
err = ErrTooManyFiles{len(names)}
return
}
files = make([]NamedReader, len(names))
var file *os.File
var stat os.FileInfo
for idx, name := range names {
file, err = os.Open(name)
if err != nil {
return
}
stat, err = file.Stat()
if err != nil {
return
}
if stat.Size() > FileUploadLimit {
err = ErrFileTooBig{file.Name(), uint64(stat.Size())}
return
}
var bb bytes.Buffer
_, err = io.Copy(&bb, file)
if err != nil {
return
}
files[idx] = NamedReader{bytes.NewReader(bb.Bytes()), name}
err = file.Close()
if err != nil {
return
}
}
return
}
// ErrFileTooBig thrown when file exceeds hardcoded filesize limit
type ErrFileTooBig struct {
Filename string
Filesize uint64
}
var sizes = []string{"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"}
var fileUploadLimitSize = humanateBytes(FileUploadLimit, 1024, sizes)
func (e ErrFileTooBig) Error() string {
return fmt.Sprintf("[pre-flight] File '%s' exceeds upload limit (%s > %s)", e.Filename, humanateBytes(e.Filesize, 1024, sizes), fileUploadLimitSize)
}
func logn(n, b float64) float64 {
return math.Log(n) / math.Log(b)
}
func humanateBytes(s uint64, base float64, sizes []string) string {
if s < 10 {
return fmt.Sprintf("%d B", s)
}
e := math.Floor(logn(float64(s), base))
suffix := sizes[int(e)]
val := math.Floor(float64(s)/math.Pow(base, e)*10+0.5) / 10
f := "%.0f %s"
if val < 10 {
f = "%.1f %s"
}
return fmt.Sprintf(f, val, suffix)
}
// ErrTooManyFiles thrown when file count in upload exceeds filecount limit
type ErrTooManyFiles struct {
Count int
}
func (e ErrTooManyFiles) Error() string {
return fmt.Sprintf("[pre-flight] Too many files (%d > %d)", e.Count, FileCountLimit)
}