forked from SpirentOrion/luddite
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnegotiator.go
42 lines (34 loc) · 1.07 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
package luddite
import (
"net/http"
"github.com/K-Phoen/negotiation"
)
// FormatNegotiator is middleware that handles Content-Type negotiation.
type FormatNegotiator struct {
acceptedFormats []string
}
// RegisterFormat registers a new format and associated MIME types.
func RegisterFormat(format string, mimeTypes []string) {
negotiation.RegisterFormat(format, mimeTypes)
}
// NewNegotiator returns a new FormatNegotiator instance.
func NewNegotiator(acceptedFormats []string) *FormatNegotiator {
return &FormatNegotiator{
acceptedFormats: acceptedFormats,
}
}
func (n *FormatNegotiator) HandleHTTP(rw http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
// If no Accept header was included, default to the first accepted format
accept := req.Header.Get(HeaderAccept)
if accept == "" {
accept = n.acceptedFormats[0]
}
// Negotiate and set a Content-Type
format, err := negotiation.NegotiateAccept(accept, n.acceptedFormats)
if err != nil {
rw.WriteHeader(http.StatusNotAcceptable)
return
}
rw.Header().Set(HeaderContentType, format.Value)
next(rw, req)
}