func (n notFoundHandler) ServeHTTP(writer http.ResponseWriter, request *http.Request) { // TODO answer with a 406 here? accept := request.Header.Get("accept") // Default to JSON. contentType := "application/json" if accept == "*/*" || accept == "" { // Force json if it can take anything. accept = "application/json" } format, err := negotiation.NegotiateAccept(accept, SupportedContentTypes) var marshaller Marshaller defaultMarshaller := ContentTypeMarshallers["application/json"] if err == nil { contentType = format.Value writer.Header().Set("Content-Type", contentType) marshaller = ContentTypeMarshallers[contentType] } // Error in negotiation or marshaller not found. if err != nil || marshaller == nil { // This should never happen... Just in case... log.Infof("No marshaler for [%s] found in %s, %s\n", contentType, ContentTypeMarshallers, ContentTypeMarshallers["application/json"]) writer.WriteHeader(http.StatusUnsupportedMediaType) sct := SupportedContentTypesMessage dataOut, _ := defaultMarshaller.Marshal(sct) writer.Write(dataOut) return } dataOut, _ := marshaller.Marshal(NewError404("URI", request.RequestURI)) writer.Write(dataOut) return }
func (negotiator NegotiatorMiddleware) ServeHTTP(writer http.ResponseWriter, request *http.Request, next http.HandlerFunc) { // TODO answer with a 406 here? accept := request.Header.Get("accept") if accept == "*/*" || accept == "" { // Force json if it can take anything. accept = "application/json" } format, err := negotiation.NegotiateAccept(accept, supportedContentTypes) if err == nil { writer.Header().Set("Content-Type", format.Value) } next(writer, request) }
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)) } }