Skip to content

Commit

Permalink
Merge pull request #2 from 9iksans/feat/svg
Browse files Browse the repository at this point in the history
add validator for .svg file
  • Loading branch information
wuriyanto48 authored Jan 11, 2023
2 parents 5b8e87f + cadb012 commit 50d1489
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 0 deletions.
5 changes: 5 additions & 0 deletions signature.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package filesig

import "regexp"

var (
AVIF = []byte{0x00, 0x00, 0x00}
BMP = []byte{0x42, 0x4D}
Expand Down Expand Up @@ -32,4 +34,7 @@ var (
ZIP_1 = []byte{0x50, 0x4B, 0x05, 0x06}
ZIP_2 = []byte{0x50, 0x4B, 0x07, 0x08}
WEBP = []byte{0x52, 0x49, 0x46, 0x46}

HtmlCommentRegex = regexp.MustCompile(`(?i)<!--([\s\S]*?)-->`)
SvgRegex = regexp.MustCompile(`(?i)^\s*(?:<\?xml[^>]*>\s*)?(?:<!doctype svg[^>]*>\s*)?<svg[^>]*>[^*]*<\/svg>\s*$`)
)
11 changes: 11 additions & 0 deletions validator.go
Original file line number Diff line number Diff line change
Expand Up @@ -211,3 +211,14 @@ func IsMp4(r io.ReadSeeker) bool {

return validMpFour1 == 0 && validMpFour2 == 0
}

// IsSvg function will return true if File is a valid SVG
func IsSvg(r io.ReadSeeker) bool {
buff, err := io.ReadAll(r)
if err != nil {
return false
}
r.Seek(0, io.SeekStart)

return SvgRegex.Match(HtmlCommentRegex.ReplaceAll(buff, []byte{}))
}
17 changes: 17 additions & 0 deletions validator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -395,3 +395,20 @@ func TestGenericMultipleCompareBuffer(t *testing.T) {
t.Error("error: one of buffer type is invalid")
}
}

func TestIsSvg(t *testing.T) {
buff, err := os.Open("./tmp/sample-0.svg")

if err != nil {
t.Error("error: SVG file not found")
}

defer func() {
buff.Close()
}()

valid := IsSvg(buff)
if !valid {
t.Error("error: buffer not valid SVG file")
}
}

0 comments on commit 50d1489

Please sign in to comment.