4
4
package typesniffer
5
5
6
6
import (
7
+ "bytes"
7
8
"fmt"
8
9
"io"
9
10
"net/http"
@@ -25,8 +26,8 @@ const (
25
26
26
27
var (
27
28
svgComment = regexp .MustCompile (`(?s)<!--.*?-->` )
28
- svgTagRegex = regexp .MustCompile (`(?si)\A\s*(?:(<!DOCTYPE\s+svg([\s:]+.*?>|>))\s*)*<svg[\s>/] ` )
29
- svgTagInXMLRegex = regexp .MustCompile (`(?si)\A<\?xml\b.*?\?>\s*(?:(<!DOCTYPE\s+svg([\s:]+.*?>|>))\s*)*<svg[\s>/] ` )
29
+ svgTagRegex = regexp .MustCompile (`(?si)\A\s*(?:(<!DOCTYPE\s+svg([\s:]+.*?>|>))\s*)*<svg\b ` )
30
+ svgTagInXMLRegex = regexp .MustCompile (`(?si)\A<\?xml\b.*?\?>\s*(?:(<!DOCTYPE\s+svg([\s:]+.*?>|>))\s*)*<svg\b ` )
30
31
)
31
32
32
33
// SniffedType contains information about a blobs type.
@@ -80,6 +81,8 @@ func (ct SniffedType) GetMimeType() string {
80
81
return strings .SplitN (ct .contentType , ";" , 2 )[0 ]
81
82
}
82
83
84
+ var svgCloseTag = []byte ("</svg>" )
85
+
83
86
// DetectContentType extends http.DetectContentType with more content types. Defaults to text/unknown if input is empty.
84
87
func DetectContentType (data []byte ) SniffedType {
85
88
if len (data ) == 0 {
@@ -94,16 +97,16 @@ func DetectContentType(data []byte) SniffedType {
94
97
95
98
// SVG is unsupported by http.DetectContentType, https://github.com/golang/go/issues/15888
96
99
97
- if strings .Contains (ct , "text/plain" ) || strings .Contains (ct , "text/html" ) {
98
- dataNoComment := svgComment . ReplaceAll ( data , nil )
99
- if svgTagRegex . Match ( dataNoComment ) {
100
- ct = SvgMimeType
101
- }
102
- }
103
- if strings . Contains ( ct , "text/xml" ) {
104
- dataNoComment := svgComment . ReplaceAll ( data , nil )
105
- if svgTagInXMLRegex . Match ( dataNoComment ) {
106
- ct = SvgMimeType
100
+ detectByHTML := strings .Contains (ct , "text/plain" ) || strings .Contains (ct , "text/html" )
101
+ detectByXML := strings . Contains ( ct , "text/xml" )
102
+ if detectByHTML || detectByXML {
103
+ dataProcessed := svgComment . ReplaceAll ( data , nil )
104
+ dataProcessed = bytes . TrimSpace ( dataProcessed )
105
+ if bytes . HasSuffix ( dataProcessed , svgCloseTag ) {
106
+ if detectByHTML && svgTagRegex . Match ( dataProcessed ) ||
107
+ detectByXML && svgTagInXMLRegex . Match ( dataProcessed ) {
108
+ ct = SvgMimeType
109
+ }
107
110
}
108
111
}
109
112
0 commit comments