Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
merged 2 commits into from
Jun 4, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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