-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmime.go
59 lines (46 loc) · 973 Bytes
/
mime.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
package xun
import (
"mime"
"net/http"
"path/filepath"
"strings"
)
type MimeType struct {
Type string
SubType string
}
func NewMimeType(t string) MimeType {
items := strings.Split(t, "/")
mt := MimeType{
Type: items[0],
SubType: "*",
}
if len(items) > 1 {
mt.SubType = items[1]
}
return mt
}
func (m *MimeType) Match(accept MimeType) bool {
if m.Type != accept.Type && (m.Type != "*" && accept.Type != "*") {
return false
}
if m.SubType == accept.SubType || (m.SubType == "*" || accept.SubType == "*") {
return true
}
return false
}
func (m *MimeType) String() string {
return m.Type + "/" + m.SubType
}
func GetMimeType(file string, buf []byte) (MimeType, string) {
mt := mime.TypeByExtension(filepath.Ext(file))
if mt == "" {
mt = http.DetectContentType(buf)
}
// text/plain; charset=utf-8
i := strings.Index(mt, ";")
if i == -1 {
return NewMimeType(mt), "; charset=utf-8"
}
return NewMimeType(mt[:i]), mt[i:]
}