-
Notifications
You must be signed in to change notification settings - Fork 26
/
header.go
45 lines (41 loc) · 983 Bytes
/
header.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
package find
import (
"fmt"
"mime"
"net/http"
"strings"
)
const (
mediaTypeNDJson = "application/x-ndjson"
mediaTypeJson = "application/json"
mediaTypeAny = "*/*"
)
func acceptsAnyOf(w http.ResponseWriter, r *http.Request, strict bool, mts ...string) (string, bool) {
values := r.Header.Values("Accept")
if len(values) == 0 {
if !strict || len(mts) == 0 {
return "", true
}
}
mtSet := make(map[string]struct{})
for _, accept := range values {
amts := strings.Split(accept, ",")
for _, amt := range amts {
mt, _, err := mime.ParseMediaType(amt)
if err != nil {
err = fmt.Errorf("invalid accept header: %s", err)
http.Error(w, err.Error(), http.StatusNotAcceptable)
return "", false
}
mtSet[mt] = struct{}{}
}
}
for _, mt := range mts {
if _, ok := mtSet[mt]; ok {
return mt, true
}
}
err := fmt.Errorf("accept: %s", strings.Join(mts, ", "))
http.Error(w, err.Error(), http.StatusNotAcceptable)
return "", false
}