diff --git a/jsr311.go b/jsr311.go index 9cfd59a1..07a0c91e 100644 --- a/jsr311.go +++ b/jsr311.go @@ -151,6 +151,16 @@ func (r RouterJSR311) detectRoute(routes []Route, httpRequest *http.Request) (*R for _, candidate := range previous { available = append(available, candidate.Produces...) } + // if POST,PUT,PATCH without body + method, length := httpRequest.Method, httpRequest.Header.Get("Content-Length") + if (method == http.MethodPost || + method == http.MethodPut || + method == http.MethodPatch) && length == "" { + return nil, NewError( + http.StatusUnsupportedMediaType, + fmt.Sprintf("415: Unsupported Media Type\n\nAvailable representations: %s", strings.Join(available, ", ")), + ) + } return nil, NewError( http.StatusNotAcceptable, fmt.Sprintf("406: Not Acceptable\n\nAvailable representations: %s", strings.Join(available, ", ")), diff --git a/web_service_test.go b/web_service_test.go index c32fab3a..f316d26d 100644 --- a/web_service_test.go +++ b/web_service_test.go @@ -124,6 +124,20 @@ Available representations: text/plain, application/json` } } +func TestUnsupportedMedia_Issue492(t *testing.T) { + tearDown() + Add(newPostTestService()) + for _, method := range []string{"POST", "PUT", "PATCH"} { + httpRequest, _ := http.NewRequest(method, "http://here.com/test", nil) + httpRequest.Header.Set("Accept", "application/json") + httpWriter := httptest.NewRecorder() + DefaultContainer.dispatch(httpWriter, httpRequest) + if 415 != httpWriter.Code { + t.Errorf("[%s] 415 expected got %d", method, httpWriter.Code) + } + } +} + func TestSelectedRoutePath_Issue100(t *testing.T) { tearDown() Add(newSelectedRouteTestingService()) @@ -376,6 +390,16 @@ func newPostNoConsumesService() *WebService { return ws } +func newPostTestService() *WebService { + ws := new(WebService).Path("") + ws.Consumes("application/json") + ws.Produces("application/json") + ws.Route(ws.POST("/test").To(doNothing)) + ws.Route(ws.PUT("/test").To(doNothing)) + ws.Route(ws.PATCH("/test").To(doNothing)) + return ws +} + func newSelectedRouteTestingService() *WebService { ws := new(WebService).Path("") ws.Route(ws.GET(pathGetFriends).To(selectedRouteChecker))