forked from thedevsaddam/govalidator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
validate_file.go
73 lines (69 loc) · 1.71 KB
/
validate_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
package govalidator
import (
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
)
// validateFiles validate file size, mimes, extension etc
func validateFiles(r *http.Request, field, rule, msg string, errsBag url.Values) {
_, _, ext, mime, size, fErr := getFileInfo(r, field)
// check size
if strings.HasPrefix(rule, "size:") {
l, err := strconv.ParseInt(strings.TrimPrefix(rule, "size:"), 10, 64)
if err != nil {
panic(errStringToInt)
}
if size > l {
if msg != "" {
errsBag.Add(field, msg)
} else {
errsBag.Add(field, fmt.Sprintf("The %s field size is can not be greater than %d bytes", field, l))
}
}
if fErr != nil {
errsBag.Add(field, fmt.Sprintf("The %s field failed to read file when fetching size", field))
}
}
// check extension
if strings.HasPrefix(rule, "ext:") {
exts := strings.Split(strings.TrimPrefix(rule, "ext:"), ",")
f := false
for _, e := range exts {
if e == ext {
f = true
}
}
if !f {
if msg != "" {
errsBag.Add(field, msg)
} else {
errsBag.Add(field, fmt.Sprintf("The %s field file extension %s is invalid", field, ext))
}
}
if fErr != nil {
errsBag.Add(field, fmt.Sprintf("The %s field failed to read file when fetching extension", field))
}
}
// check mimes
if strings.HasPrefix(rule, "mime:") {
mimes := strings.Split(strings.TrimPrefix(rule, "mime:"), ",")
f := false
for _, m := range mimes {
if m == mime {
f = true
}
}
if !f {
if msg != "" {
errsBag.Add(field, msg)
} else {
errsBag.Add(field, fmt.Sprintf("The %s field file mime %s is invalid", field, mime))
}
}
if fErr != nil {
errsBag.Add(field, fmt.Sprintf("The %s field failed to read file when fetching mime", field))
}
}
}