Skip to content

Response body uses a NopCloser, prevents detecting http: read on closed response body errors #124

Description

@zacharyarnaise

gock uses a ioutil.NopCloser for its response bodies:

gock/responder.go

Lines 107 to 111 in 0c43888

// createReadCloser creates an io.ReadCloser from a byte slice that is suitable for use as an
// http response body.
func createReadCloser(body []byte) io.ReadCloser {
return ioutil.NopCloser(bytes.NewReader(body))
}

This makes it very hard to catch faulty code which would try to read on a response's body after it's been closed:

func TestHTTP(t *testing.T) {
	gock.Intercept()
	gock.Observe(gock.DumpRequest)

	gock.New("https://httpbin.org").
		Get("/get").
		Reply(200).
		JSON(map[string]string{"foo": "bar"})

	resp, err := http.Get("https://httpbin.org/get")
	require.NoError(t, err)
	resp.Body.Close()

	body := map[string]string{}
	require.NoError(t, json.NewDecoder(resp.Body).Decode(&body)) // this should fail
	assert.Equal(t, map[string]string{"foo": "bar"}, body)
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions