Skip to content

Commit

Permalink
Fixing resp body reuse (#147)
Browse files Browse the repository at this point in the history
  • Loading branch information
Mzack9999 authored May 8, 2023
1 parent 9a7cd71 commit 8e10748
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
5 changes: 5 additions & 0 deletions http/httputil.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,14 @@ func DumpResponseHeadersAndRaw(resp *http.Response) (headers, fullresp []byte, e
if err == nil {
_ = b.Close()
}

// rewind the body to allow full dump
resp.Body = io.NopCloser(bytes.NewReader(buf1.Bytes()))
err = resp.Write(&buf2)
fullresp = buf2.Bytes()

// rewind once more to allow further reuses
resp.Body = io.NopCloser(bytes.NewReader(buf1.Bytes()))
return
}

Expand Down
9 changes: 8 additions & 1 deletion http/httputil_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package httputil

import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
Expand All @@ -20,9 +21,10 @@ func TestDumpRequest(t *testing.T) {
}

func TestDumpResponseHeadersAndRaw(t *testing.T) {
expectedResponseBody := "Hello, client"
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Del("Date")
fmt.Fprintln(w, "Hello, client")
fmt.Fprintln(w, expectedResponseBody)
}))
defer ts.Close()

Expand All @@ -45,4 +47,9 @@ func TestDumpResponseHeadersAndRaw(t *testing.T) {
resp := "HTTP/1.1 200 OK\r\nContent-Length: 14\r\nContent-Type: text/plain; charset=utf-8\r\n\r\nHello, client\n\r\n"
require.Equal(t, headers, headersdump)
require.Equal(t, resp, respdump)

// ensure that the response body is still readable
respBody, err := io.ReadAll(res.Body)
require.Nil(t, err)
require.Equal(t, expectedResponseBody+"\n", string(respBody))
}

0 comments on commit 8e10748

Please sign in to comment.