Skip to content

Commit

Permalink
Do not reset response body (#40)
Browse files Browse the repository at this point in the history
* Do not reset response body on EOF

* Use NopCloser

* Fix gofmt issue
  • Loading branch information
iliacimpoes authored and h2non committed Oct 29, 2018
1 parent e65e3a2 commit 65dac6c
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 20 deletions.
22 changes: 2 additions & 20 deletions responder.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package gock
import (
"bytes"
"io"
"io/ioutil"
"net/http"
"strconv"
"time"
Expand Down Expand Up @@ -82,24 +83,5 @@ func mergeHeaders(res *http.Response, mres *Response) http.Header {
// 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 &dummyReadCloser{body: bytes.NewReader(body)}
}

// dummyReadCloser is used internally as io.ReadCloser capable interface for bodies.
type dummyReadCloser struct {
body io.ReadSeeker
}

// Read implements the required method by io.ReadClose interface.
func (d *dummyReadCloser) Read(p []byte) (n int, err error) {
n, err = d.body.Read(p)
if err == io.EOF {
d.body.Seek(0, 0)
}
return n, err
}

// Close implements a no-op required method by io.ReadClose interface.
func (d *dummyReadCloser) Close() error {
return nil
return ioutil.NopCloser(bytes.NewReader(body))
}
18 changes: 18 additions & 0 deletions responder_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,24 @@ func TestResponder(t *testing.T) {
st.Expect(t, string(body), "foo")
}

func TestResponder_ReadTwice(t *testing.T) {
defer after()
mres := New("http://foo.com").Reply(200).BodyString("foo")
req := &http.Request{}

res, err := Responder(req, mres, nil)
st.Expect(t, err, nil)
st.Expect(t, res.Status, "200 OK")
st.Expect(t, res.StatusCode, 200)

body, _ := ioutil.ReadAll(res.Body)
st.Expect(t, string(body), "foo")

body, err = ioutil.ReadAll(res.Body)
st.Expect(t, err, nil)
st.Expect(t, body, []byte{})
}

func TestResponderSupportsMultipleHeadersWithSameKey(t *testing.T) {
defer after()
mres := New("http://foo").
Expand Down

0 comments on commit 65dac6c

Please sign in to comment.