-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaccept.go
58 lines (48 loc) · 1.25 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
package middleware
import (
"net/http"
"darvaza.org/x/web/qlist"
)
// AcceptMiddleware filters the Accept header to only include those
func AcceptMiddleware(supported ...string) func(http.Handler) http.Handler {
valid, fallback := acceptSupportedAsRanges(supported)
if len(valid) == 0 {
return NOOP
}
return func(next http.Handler) http.Handler {
h := func(rw http.ResponseWriter, req *http.Request) {
acceptMiddlewareHandler(rw, req, next, valid, fallback)
}
return http.HandlerFunc(h)
}
}
func acceptSupportedAsRanges(supported []string) (out []qlist.QualityValue, fallback string) {
out = make([]qlist.QualityValue, 0, len(supported))
for _, s := range supported {
r, err := qlist.ParseMediaRange(s)
if err == nil {
if len(out) == 0 {
fallback = s
}
out = append(out, r)
}
}
return out, fallback
}
func acceptMiddlewareHandler(rw http.ResponseWriter, req *http.Request,
next http.Handler, supported []qlist.QualityValue,
fallback string) {
//
var s string
if len(supported) > 0 {
accepted, _ := qlist.ParseMediaRangeHeader(req.Header)
if len(accepted) > 0 {
s, _, _ = qlist.BestQualityParsed(supported, accepted)
}
}
if s == "" {
s = fallback
}
req.Header[qlist.Accept] = []string{s}
next.ServeHTTP(rw, req)
}