Skip to content

Commit

Permalink
Merge pull request #36 from rusenask/feature/fixing_response_body
Browse files Browse the repository at this point in the history
Feature/fixing response body
  • Loading branch information
Karolis Rusenas committed Dec 29, 2015
2 parents b3c1126 + 144f62f commit dda524d
Showing 1 changed file with 32 additions and 4 deletions.
36 changes: 32 additions & 4 deletions models.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import (
"fmt"
"io"
"net/http"
"net/http/httputil"

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

if err == nil {

// getting response body
respBody, err := httputil.DumpResponse(resp, true)
respBody, err := extractBody(resp)
if err != nil {
// copying the response body did not work
if err != nil {
Expand All @@ -106,6 +103,37 @@ func (d *DBClient) captureRequest(req *http.Request) (*http.Response, error) {
return resp, err
}

func copyBody(body io.ReadCloser) (resp1, resp2 io.ReadCloser, err error) {
var buf bytes.Buffer
if _, err = buf.ReadFrom(body); err != nil {
return nil, nil, err
}
if err = body.Close(); err != nil {
return nil, nil, err
}
return ioutil.NopCloser(&buf), ioutil.NopCloser(bytes.NewReader(buf.Bytes())), nil
}

func extractBody(resp *http.Response) (extract []byte, err error) {
save := resp.Body
savecl := resp.ContentLength

save, resp.Body, err = copyBody(resp.Body)

if err != nil {
return
}
defer resp.Body.Close()
extract, err = ioutil.ReadAll(resp.Body)

resp.Body = save
resp.ContentLength = savecl
if err != nil {
return nil, err
}
return extract, nil
}

// doRequest performs original request and returns response that should be returned to client and error (if there is one)
func (d *DBClient) doRequest(request *http.Request) (*http.Response, error) {
// We can't have this set. And it only contains "/pkg/net/http/" anyway
Expand Down

0 comments on commit dda524d

Please sign in to comment.