Skip to content

Commit 50d1489

Browse files
authored
Merge pull request #2 from 9iksans/feat/svg
add validator for .svg file
2 parents 5b8e87f + cadb012 commit 50d1489

File tree

3 files changed

+33
-0
lines changed

3 files changed

+33
-0
lines changed

signature.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
package filesig
22

3+
import "regexp"
4+
35
var (
46
AVIF = []byte{0x00, 0x00, 0x00}
57
BMP = []byte{0x42, 0x4D}
@@ -32,4 +34,7 @@ var (
3234
ZIP_1 = []byte{0x50, 0x4B, 0x05, 0x06}
3335
ZIP_2 = []byte{0x50, 0x4B, 0x07, 0x08}
3436
WEBP = []byte{0x52, 0x49, 0x46, 0x46}
37+
38+
HtmlCommentRegex = regexp.MustCompile(`(?i)<!--([\s\S]*?)-->`)
39+
SvgRegex = regexp.MustCompile(`(?i)^\s*(?:<\?xml[^>]*>\s*)?(?:<!doctype svg[^>]*>\s*)?<svg[^>]*>[^*]*<\/svg>\s*$`)
3540
)

validator.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -211,3 +211,14 @@ func IsMp4(r io.ReadSeeker) bool {
211211

212212
return validMpFour1 == 0 && validMpFour2 == 0
213213
}
214+
215+
// IsSvg function will return true if File is a valid SVG
216+
func IsSvg(r io.ReadSeeker) bool {
217+
buff, err := io.ReadAll(r)
218+
if err != nil {
219+
return false
220+
}
221+
r.Seek(0, io.SeekStart)
222+
223+
return SvgRegex.Match(HtmlCommentRegex.ReplaceAll(buff, []byte{}))
224+
}

validator_test.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -395,3 +395,20 @@ func TestGenericMultipleCompareBuffer(t *testing.T) {
395395
t.Error("error: one of buffer type is invalid")
396396
}
397397
}
398+
399+
func TestIsSvg(t *testing.T) {
400+
buff, err := os.Open("./tmp/sample-0.svg")
401+
402+
if err != nil {
403+
t.Error("error: SVG file not found")
404+
}
405+
406+
defer func() {
407+
buff.Close()
408+
}()
409+
410+
valid := IsSvg(buff)
411+
if !valid {
412+
t.Error("error: buffer not valid SVG file")
413+
}
414+
}

0 commit comments

Comments
 (0)