This repository has been archived by the owner on Aug 3, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
accept.go
189 lines (168 loc) · 4.33 KB
/
accept.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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
// Copyright 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package goscaffold
import (
"net/http"
"regexp"
"sort"
"strconv"
"strings"
)
var qParamRe = regexp.MustCompile("^q=([0-9\\.]+)$")
type acceptCriterion struct {
major string
minor string
precedence float32
origOrder int
match string
}
type acceptCriteria []acceptCriterion
/*
SelectMediaType matches a set of candidate media types against the
Accept header in an HTTP request. It does this using the rules from
RFC2616 section 1.4.
If no Accept header is present, then the first choice in the
"choices" array is returned.
If multiple choices match, then we will take the first one specified
in the "Accept" header.
If there are no compatible media types, then an empty string
is returned.
Only the first "Accept" header on the request is considered.
*/
func SelectMediaType(req *http.Request, choices []string) string {
hdr := strings.TrimSpace(req.Header.Get("Accept"))
if hdr == "" || hdr == "*" || hdr == "*/*" {
if len(choices) >= 1 {
return choices[0]
}
return ""
}
// Parse accept header and parse the criteria
candidates := parseAcceptHeader(hdr)
// For each choice, assign the best match (least wildcardy)
matches := make(map[string]*acceptCriterion)
for _, choice := range choices {
for c := range candidates {
crit := candidates[c]
if crit.matches(choice) {
if matches[choice] == nil ||
matches[choice].level() < crit.level() {
matches[choice] = &acceptCriterion{
minor: crit.minor,
major: crit.major,
precedence: crit.precedence,
origOrder: crit.origOrder,
match: choice,
}
}
}
}
}
if len(matches) == 0 {
return ""
}
// Sort the matches now by precedence level and original order
var sortedMatches acceptCriteria
for _, v := range matches {
sortedMatches = append(sortedMatches, *v)
}
sortedMatches.sort()
return sortedMatches[0].match
}
func parseAcceptHeader(hdr string) acceptCriteria {
var ret acceptCriteria
parts := strings.Split(hdr, ",")
for i, part := range parts {
candidate := parseAcceptPart(part, i)
ret = append(ret, candidate)
}
return ret
}
/*
parseAcceptPart parses a single section of the header and extracts the
"q" parameter.
*/
func parseAcceptPart(part string, order int) acceptCriterion {
params := strings.Split(part, ";")
finalType := strings.TrimSpace(params[0])
var precedence float32 = 1.0
for _, param := range params[1:] {
match := qParamRe.FindStringSubmatch(strings.TrimSpace(param))
if match == nil {
finalType += ";" + param
} else {
qVal, err := strconv.ParseFloat(match[1], 32)
if err == nil {
precedence = float32(qVal)
}
}
}
splitType := strings.SplitN(finalType, "/", 2)
return acceptCriterion{
major: splitType[0],
minor: splitType[1],
precedence: precedence,
origOrder: order,
}
}
/*
matches matches a candidate media type with a criterion.
*/
func (a acceptCriterion) matches(t string) bool {
st := strings.SplitN(t, "/", 2)
if a.major != "*" && a.major != st[0] {
return false
}
if a.minor != "*" && a.minor != st[1] {
return false
}
return true
}
func (a acceptCriterion) level() int {
if a.minor == "*" {
if a.major == "*" {
return 0
}
return 1
}
return 2
}
/*
sortCandidates sorts accept header candidates in order of:
1) Precedence (from the "q" parameter)
2) Original order in accept header
3) Stable sort otherwise
*/
func (c acceptCriteria) sort() {
sort.Stable(c)
}
func (c acceptCriteria) Less(i, j int) bool {
// Higher precedence goes first
if c[i].precedence > c[j].precedence {
return true
}
if c[i].precedence == c[j].precedence &&
c[i].origOrder < c[j].origOrder {
return true
}
return false
}
func (c acceptCriteria) Len() int {
return len(c)
}
func (c acceptCriteria) Swap(i, j int) {
tmp := c[i]
c[i] = c[j]
c[j] = tmp
}