forked from go-ozzo/ozzo-routing
-
Notifications
You must be signed in to change notification settings - Fork 0
/
negotiator.go
176 lines (153 loc) · 4.68 KB
/
negotiator.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
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package content
import (
"net/http"
"strconv"
"strings"
)
// AcceptRange represents an accept range as defined in https://tools.ietf.org/html/rfc7231#section-5.3.2
//
// Accept = #( media-range [ accept-params ] )
// media-range = ( "*/*"
// / ( type "/" "*" )
// / ( type "/" subtype )
// ) *( OWS ";" OWS parameter )
// accept-params = weight *( accept-ext )
// accept-ext = OWS ";" OWS token [ "=" ( token / quoted-string ) ]
type AcceptRange struct {
Type string
Subtype string
Weight float64
Parameters map[string]string
raw string // the raw string for this accept
}
// RawString returns the raw string in the request specifying the accept range.
func (a AcceptRange) RawString() string {
return a.raw
}
// AcceptMediaTypes builds a list of AcceptRange from the given HTTP request.
func AcceptMediaTypes(r *http.Request) []AcceptRange {
result := []AcceptRange{}
for _, v := range r.Header["Accept"] {
result = append(result, ParseAcceptRanges(v)...)
}
return result
}
// ParseAcceptRanges parses an Accept header into a list of AcceptRange
func ParseAcceptRanges(accepts string) []AcceptRange {
result := []AcceptRange{}
remaining := accepts
for {
var accept string
accept, remaining = extractFieldAndSkipToken(remaining, ',')
result = append(result, ParseAcceptRange(accept))
if len(remaining) == 0 {
break
}
}
return result
}
// ParseAcceptRange parses a single accept string into an AcceptRange.
func ParseAcceptRange(accept string) AcceptRange {
typeAndSub, rawparams := extractFieldAndSkipToken(accept, ';')
tp, subtp := extractFieldAndSkipToken(typeAndSub, '/')
params := extractParams(rawparams)
w := extractWeight(params)
return AcceptRange{Type: tp, Subtype: subtp, Parameters: params, Weight: w, raw: accept}
}
func extractWeight(params map[string]string) float64 {
if w, ok := params["q"]; ok {
res, err := strconv.ParseFloat(w, 64)
if err == nil {
return res
}
}
return 1 // default is 1
}
func extractParams(raw string) map[string]string {
params := map[string]string{}
rest := raw
for {
var p string
p, rest = extractFieldAndSkipToken(rest, ';')
if len(p) > 0 {
k, v := extractFieldAndSkipToken(p, '=')
params[k] = v
}
if len(rest) == 0 {
break
}
}
return params
}
func extractFieldAndSkipToken(s string, sep rune) (string, string) {
f, r := extractField(s, sep)
if len(r) > 0 {
r = r[1:]
}
return f, r
}
func extractField(s string, sep rune) (field, rest string) {
field = s
for i, v := range s {
if v == sep {
field = strings.TrimSpace(s[:i])
rest = strings.TrimSpace(s[i:])
break
}
}
return
}
func compareParams(params1 map[string]string, params2 map[string]string) (count int) {
for k1, v1 := range params1 {
if v2, ok := params2[k1]; ok && v1 == v2 {
count++
}
}
return count
}
// NegotiateContentType negotiates the content types based on the given request and allowed types.
func NegotiateContentType(r *http.Request, offers []string, defaultOffer string) string {
accepts := AcceptMediaTypes(r)
offerRanges := []AcceptRange{}
for _, off := range offers {
offerRanges = append(offerRanges, ParseAcceptRange(off))
}
return negotiateContentType(accepts, offerRanges, ParseAcceptRange(defaultOffer))
}
func negotiateContentType(accepts []AcceptRange, offers []AcceptRange, defaultOffer AcceptRange) string {
best := defaultOffer.RawString()
bestWeight := defaultOffer.Weight
bestParams := 0
for _, offer := range offers {
for _, accept := range accepts {
// add a booster on the weights to prefer more exact matches to wildcards
// such that: */* = 0, x/* = 1, x/x = 2
booster := float64(0)
if accept.Type != "*" {
booster++
if accept.Subtype != "*" {
booster++
}
}
if bestWeight > (accept.Weight + booster) {
continue // we already have something better..
} else if accept.Type == "*" && accept.Subtype == "*" && ((accept.Weight + booster) > bestWeight) {
best = offer.RawString()
bestWeight = accept.Weight + booster
} else if accept.Subtype == "*" && offer.Type == accept.Type && ((accept.Weight + booster) > bestWeight) {
best = offer.RawString()
bestWeight = accept.Weight + booster
} else if accept.Type == offer.Type && accept.Subtype == offer.Subtype {
paramCount := compareParams(accept.Parameters, offer.Parameters)
if paramCount >= bestParams { // if it's equal this one must be better, since the weight was better..
best = offer.RawString()
bestWeight = accept.Weight + booster
bestParams = paramCount
}
}
}
}
return best
}