Skip to content

Commit

Permalink
add test and fix for POST without body and Content-type, issue #492 (#…
Browse files Browse the repository at this point in the history
…496)

* add test and fix for POST without body and Content-type, issue #492

* rm delete
  • Loading branch information
emicklei authored Jun 4, 2022
1 parent f04c271 commit c2c010a
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
10 changes: 10 additions & 0 deletions jsr311.go
Original file line number Diff line number Diff line change
Expand Up @@ -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, ", ")),
Expand Down
24 changes: 24 additions & 0 deletions web_service_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Expand Down Expand Up @@ -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))
Expand Down

0 comments on commit c2c010a

Please sign in to comment.