-
Notifications
You must be signed in to change notification settings - Fork 1
/
sage.go
114 lines (94 loc) · 2.28 KB
/
sage.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
package sage
import (
"io"
"mime/multipart"
"net/http"
"os"
"slices"
"strconv"
"strings"
"github.com/insanXYZ/sage/throw"
)
var (
tagSupport = []string{"png", "jpeg", "gif", "jpg", "bmp"}
tagWithValue = []string{"minsize", "maxsize"}
)
func Validate(file interface{}, tag ...string) error {
switch t := file.(type) {
case *os.File:
stat, _ := t.Stat()
t.Seek(0, 0)
return valid(t, tag, stat.Size())
case *multipart.FileHeader:
open, err := t.Open()
if err != nil {
return err
}
defer open.Close()
defer open.Seek(0, 0)
return valid(open, tag, t.Size)
}
return throw.InvalidFile
}
func valid(file io.Reader, tags []string, size int64) error {
var t string
read, err := io.ReadAll(file)
if err != nil {
return err
}
t = http.DetectContentType(read)
splitType := strings.Split(t, "/")
if len(tags) == 0 {
if splitType[0] != "image" {
return throw.InvalidFile
}
}
if len(tags) > 0 {
for _, singleTag := range tags {
lowerStringSingleTag := strings.ToLower(singleTag)
errInvalidTag := validTag(lowerStringSingleTag)
if errInvalidTag != nil {
return errInvalidTag
}
if slices.Contains(tagSupport, lowerStringSingleTag) {
if splitType[1] != lowerStringSingleTag {
return throw.InvalidType(lowerStringSingleTag)
}
}
sliceContainWithValue := slices.ContainsFunc(tagWithValue, func(s string) bool {
return strings.Contains(lowerStringSingleTag, s)
})
if strings.Contains(lowerStringSingleTag, "=") && sliceContainWithValue {
str := strings.Split(lowerStringSingleTag, "=")
atoi, errAtoi := strconv.Atoi(str[1])
if errAtoi != nil {
return errAtoi
}
switch strings.ToLower(str[0]) {
case "minsize":
if int(size/1024) < atoi {
return throw.InvalidSize(int64(atoi), throw.Minimal)
}
case "maxsize":
if int(size/1024) > atoi {
return throw.InvalidSize(int64(atoi), throw.Maximum)
}
}
}
}
}
return nil
}
func validTag(tags string) error {
if strings.Contains(tags, "=") {
split := strings.Split(tags, "=")
if !slices.Contains(tagWithValue, split[0]) {
return throw.InvalidTag(tags)
}
tags = split[0]
}
if !slices.Contains(tagSupport, tags) || !slices.Contains(tagWithValue, tags) {
return throw.InvalidTag(tags)
}
return nil
}