-
Notifications
You must be signed in to change notification settings - Fork 173
/
mimetype.go
78 lines (62 loc) · 1.78 KB
/
mimetype.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
package image
import (
"fmt"
"io"
"mime"
"net/http"
"net/url"
"path/filepath"
"strings"
"time"
"github.com/rubenfonseca/fastimage"
)
const (
MimetypeDetectorTypeFastimage = "fastimage"
MimetypeDetectorTypeSniff = "sniff"
)
func GetMimetypeDetector(mimetypeDetectorType string) MimetypeDetectorFunc {
switch mimetypeDetectorType {
case MimetypeDetectorTypeFastimage:
return MimetypeDetectorFastimage
case MimetypeDetectorTypeSniff:
return MimetypeDetectorSniff
default:
return MimetypeDetectorExtension
}
}
type MimetypeDetectorFunc func(*url.URL) (string, error)
// Detect mimetype by looking at the URL extension
func MimetypeDetectorExtension(uri *url.URL) (string, error) {
return mime.TypeByExtension(filepath.Ext(uri.Path)), nil
}
// Detect mimetype with third-party fastimage library.
// Overhead warning: fastimage makes a request (albeit a very small partial one) upon each detection.
func MimetypeDetectorFastimage(uri *url.URL) (string, error) {
imageType, _, err := fastimage.DetectImageType(uri.String())
if err != nil {
return "", err
}
return fmt.Sprint("image/", strings.ToLower(imageType.String())), nil
}
// Detect mimetype using go native content detection which implements
// the MIME Sniffing alorithm described here: https://mimesniff.spec.whatwg.org/
func MimetypeDetectorSniff(uri *url.URL) (string, error) {
client := &http.Client{
Timeout: 5000 * time.Millisecond,
}
resp, err := client.Get(uri.String())
if err != nil {
return "", err
}
buffer := make([]byte, 512)
n, err := resp.Body.Read(buffer)
// n.b. will ignore EOF errors if buffer < 512
if err != nil && err != io.EOF {
return "", err
}
if err := resp.Body.Close(); err != nil {
return "", err
}
contentType := http.DetectContentType(buffer[:n])
return contentType, nil
}