Skip to content
Snippets Groups Projects
Commit 19ea19b7 authored by Will McCutchen's avatar Will McCutchen
Browse files

Better handling of empty request bodies

parent 7c7422c1
No related branches found
No related tags found
No related merge requests found
......@@ -323,7 +323,18 @@ func TestHeaders(t *testing.T) {
}
func TestPost__EmptyBody(t *testing.T) {
var tests = []struct {
contentType string
}{
{""},
{"application/json; charset=utf-8"},
{"application/x-www-form-urlencoded"},
{"multipart/form-data; foo"},
}
for _, test := range tests {
t.Run("content type/"+test.contentType, func(t *testing.T) {
r, _ := http.NewRequest("POST", "/post", nil)
r.Header.Set("Content-Type", test.contentType)
w := httptest.NewRecorder()
handler.ServeHTTP(w, r)
......@@ -336,12 +347,21 @@ func TestPost__EmptyBody(t *testing.T) {
t.Fatalf("failed to unmarshal body %s from JSON: %s", w.Body, err)
}
if resp.Data != "" {
t.Fatalf("expected empty response data, got %#v", resp.Data)
}
if resp.JSON != nil {
t.Fatalf("expected nil response json, got %#v", resp.JSON)
}
if len(resp.Args) > 0 {
t.Fatalf("expected no query params, got %#v", resp.Args)
}
if len(resp.Form) > 0 {
t.Fatalf("expected no form data, got %#v", resp.Form)
}
})
}
}
func TestPost__FormEncodedBody(t *testing.T) {
......
......@@ -121,7 +121,8 @@ func parseBody(w http.ResponseWriter, r *http.Request, resp *bodyResponse) error
}
resp.Form = r.PostForm
case strings.HasPrefix(ct, "application/json"):
if err := json.NewDecoder(r.Body).Decode(&resp.JSON); err != nil {
err := json.NewDecoder(r.Body).Decode(&resp.JSON)
if err != nil && err != io.EOF {
return err
}
}
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment