-
Notifications
You must be signed in to change notification settings - Fork 3
/
mimetype.go
94 lines (73 loc) · 1.93 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package mimeheader
import "mime"
// MimeParts MUST contain two parts <MIME_type>/<MIME_subtype>.
const MimeParts = 2
// MimeSeparator MUST be separated forward slash.
const MimeSeparator = "/"
// MimeAny represented as the asterisk.
const MimeAny = "*"
// MimeType structure for media type (mime type).
type MimeType struct {
Type string
Subtype string
Params map[string]string
}
func (mt MimeType) Valid() bool {
// /plain and text/ are not valid types.
if mt.Type == "" || mt.Subtype == "" {
return false
}
// */plain is not valid type.
if mt.Type == MimeAny && mt.Subtype != MimeAny {
return false
}
return true
}
// String builds mime type from type and subtype.
func (mt MimeType) String() string {
if mt.Type == "" && mt.Subtype == "" {
return ""
}
t := mt.Type
if t == "" {
t = MimeAny
}
st := mt.Subtype
if st == "" {
st = MimeAny
}
return t + MimeSeparator + st
}
// StringWithParams builds mime type from type and subtype with params.
func (mt MimeType) StringWithParams() string {
return mime.FormatMediaType(mt.String(), mt.Params)
}
// Match matches current structure with possible wildcards.
// MimeType structure (current) can be wildcard or specific type, like "text/*", "*/*", "text/plain".
func (mt MimeType) Match(target MimeType) bool {
if !matchMimePart(mt.Type, target.Type) {
return false
}
if !matchMimePart(mt.Subtype, target.Subtype) {
return false
}
return true
}
// MatchText matches current structure with possible wildcards. Target MUST be specific type, like "application/json", "text/plain"
// MimeType structure (current) can be wildcard or specific type, like "text/*", "*/*", "text/plain".
func (mt MimeType) MatchText(target string) bool {
tmtype, err := ParseMediaType(target)
if err != nil {
return false
}
return mt.Match(tmtype)
}
func matchMimePart(b, t string) bool {
if b == t {
return true
}
if b == MimeAny || t == MimeAny {
return true
}
return false
}