/
negotiate.go
34 lines (26 loc) · 899 Bytes
/
negotiate.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
package negotiate
import (
"net/http"
"github.com/K-Phoen/negotiation"
"github.com/go-martini/martini"
"github.com/martini-contrib/encoder"
)
func NegotiateFormat(negotiators map[string](encoder.Encoder)) martini.Handler {
alternatives := make([]string, 0, len(negotiators))
for key := range negotiators {
alternatives = append(alternatives, key)
}
return func(r *http.Request, c martini.Context, w http.ResponseWriter) {
if len(r.Header["Accept"]) == 0 {
w.WriteHeader(http.StatusNotAcceptable);
return
}
alternative, err := negotiation.NegotiateAccept(r.Header["Accept"][0], alternatives)
if err != nil || negotiators[alternative.Value] == nil {
w.WriteHeader(http.StatusNotAcceptable);
return
}
w.Header().Set("Content-Type", alternative.Value)
c.MapTo(negotiators[alternative.Value], (*encoder.Encoder)(nil))
}
}