From c2c010a8bf168730835fc945ba2f2d01bc764fe2 Mon Sep 17 00:00:00 2001 From: Ernest Micklei Date: Sat, 4 Jun 2022 10:29:52 +0200 Subject: [PATCH] add test and fix for POST without body and Content-type, issue #492 (#496) * add test and fix for POST without body and Content-type, issue #492 * rm delete --- jsr311.go | 10 ++++++++++ web_service_test.go | 24 ++++++++++++++++++++++++ 2 files changed, 34 insertions(+) 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))