-
Notifications
You must be signed in to change notification settings - Fork 0
/
mime.go
120 lines (97 loc) · 1.81 KB
/
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
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package encoding
import (
"sort"
"strconv"
"strings"
)
type mimeInfo struct {
mime string
typ string
sub string
q float32
}
func (m *mimeInfo) equals(info *mimeInfo) bool {
typ := info.typ == m.typ || info.typ == "*"
sub := info.sub == m.sub || info.sub == "*"
return typ && sub
}
type mimeInfoList []*mimeInfo
func (a mimeInfoList) Len() int {
return len(a)
}
func (a mimeInfoList) Less(i, j int) bool {
return a[i].q > a[j].q
}
func (a mimeInfoList) Swap(i, j int) {
a[i], a[j] = a[j], a[i]
}
func parseMimeInfo(mime string) *mimeInfo {
mime = strings.TrimSpace(mime)
i := strings.Index(mime, "/")
if i == -1 {
return nil
}
return &mimeInfo{
mime: mime,
typ: mime[:i],
sub: mime[i+1:],
q: 1,
}
}
func parseAcceptHeader(accept string) []*mimeInfo {
accept = strings.TrimSpace(accept)
if accept == "" {
return nil
}
var mimes mimeInfoList
for {
buf := accept
i := strings.Index(accept, ",")
if i != -1 {
accept, buf = accept[i+1:], accept[:i]
}
if a := parseAcceptMime(buf); a != nil {
mimes = append(mimes, a)
}
if i == -1 {
break
}
}
sort.Sort(mimes)
return []*mimeInfo(mimes)
}
func parseAcceptMime(a string) *mimeInfo {
// Parse mime as a whole
mime := ""
buf := string(a)
i := strings.Index(buf, ";")
if i != -1 {
mime, buf = strings.TrimSpace(buf[:i]), buf[i+1:]
} else {
mime = strings.TrimSpace(buf)
}
// Parse type and subtype
info := parseMimeInfo(mime)
if info == nil {
return nil
}
// Parse q
param := ""
for {
i := strings.Index(buf, ";")
if i == -1 {
param, buf = strings.TrimSpace(buf), ""
} else {
param, buf = strings.TrimSpace(buf[:i]), buf[i+1:]
}
if param[:2] == "q=" {
f, _ := strconv.ParseFloat(param[2:], 32)
info.q = float32(f)
break
}
if buf == "" {
break
}
}
return info
}