Skip to content

Commit dda524d

Browse files
author
Karolis Rusenas
committed
Merge pull request #36 from rusenask/feature/fixing_response_body
Feature/fixing response body
2 parents b3c1126 + 144f62f commit dda524d

File tree

1 file changed

+32
-4
lines changed

1 file changed

+32
-4
lines changed

models.go

Lines changed: 32 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ import (
77
"fmt"
88
"io"
99
"net/http"
10-
"net/http/httputil"
1110

1211
log "github.com/Sirupsen/logrus"
1312
"github.com/elazarl/goproxy"
@@ -86,9 +85,7 @@ func (d *DBClient) captureRequest(req *http.Request) (*http.Response, error) {
8685
resp, err := d.doRequest(req)
8786

8887
if err == nil {
89-
90-
// getting response body
91-
respBody, err := httputil.DumpResponse(resp, true)
88+
respBody, err := extractBody(resp)
9289
if err != nil {
9390
// copying the response body did not work
9491
if err != nil {
@@ -106,6 +103,37 @@ func (d *DBClient) captureRequest(req *http.Request) (*http.Response, error) {
106103
return resp, err
107104
}
108105

106+
func copyBody(body io.ReadCloser) (resp1, resp2 io.ReadCloser, err error) {
107+
var buf bytes.Buffer
108+
if _, err = buf.ReadFrom(body); err != nil {
109+
return nil, nil, err
110+
}
111+
if err = body.Close(); err != nil {
112+
return nil, nil, err
113+
}
114+
return ioutil.NopCloser(&buf), ioutil.NopCloser(bytes.NewReader(buf.Bytes())), nil
115+
}
116+
117+
func extractBody(resp *http.Response) (extract []byte, err error) {
118+
save := resp.Body
119+
savecl := resp.ContentLength
120+
121+
save, resp.Body, err = copyBody(resp.Body)
122+
123+
if err != nil {
124+
return
125+
}
126+
defer resp.Body.Close()
127+
extract, err = ioutil.ReadAll(resp.Body)
128+
129+
resp.Body = save
130+
resp.ContentLength = savecl
131+
if err != nil {
132+
return nil, err
133+
}
134+
return extract, nil
135+
}
136+
109137
// doRequest performs original request and returns response that should be returned to client and error (if there is one)
110138
func (d *DBClient) doRequest(request *http.Request) (*http.Response, error) {
111139
// We can't have this set. And it only contains "/pkg/net/http/" anyway

0 commit comments

Comments
 (0)