Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion middleware/wrap_writer.go
Original file line number Diff line number Diff line change
Expand Up @@ -208,8 +208,10 @@ func (f *http2FancyWriter) Push(target string, opts *http.PushOptions) error {

func (f *httpFancyWriter) ReadFrom(r io.Reader) (int64, error) {
if f.basicWriter.tee != nil {
// Route through basicWriter.Write so that data is also written to the
// tee writer. basicWriter.Write already increments basicWriter.bytes,
// so we must NOT add n again here (that would double-count).
n, err := io.Copy(&f.basicWriter, r)
f.basicWriter.bytes += int(n)
return n, err
}
rf := f.basicWriter.ResponseWriter.(io.ReaderFrom)
Expand Down
25 changes: 25 additions & 0 deletions middleware/wrap_writer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"net/http"
"net/http/httptest"
"strings"
"testing"
)

Expand Down Expand Up @@ -84,3 +85,27 @@ func TestBasicWriterDiscardsWritesToOriginalResponseWriter(t *testing.T) {
assertEqual(t, 11, wrap.BytesWritten())
})
}

// TestHttpFancyWriterReadFromByteCountWithTee is a regression test for
// https://github.com/go-chi/chi/issues/1067.
// httpFancyWriter.ReadFrom was adding n to basicWriter.bytes even when the
// write went through basicWriter.Write (which already increments the counter),
// resulting in double-counting the bytes when a Tee writer was set.
func TestHttpFancyWriterReadFromByteCountWithTee(t *testing.T) {
original := &httptest.ResponseRecorder{
HeaderMap: make(http.Header),
Body: new(bytes.Buffer),
}
f := &httpFancyWriter{basicWriter: basicWriter{ResponseWriter: original}}

var teeBuf bytes.Buffer
f.Tee(&teeBuf)

const input = "hello world"
n, err := f.ReadFrom(strings.NewReader(input))
assertNoError(t, err)
assertEqual(t, int64(len(input)), n)
// Before the fix, BytesWritten() returned 22 (double-counted).
assertEqual(t, len(input), f.BytesWritten())
assertEqual(t, []byte(input), teeBuf.Bytes())
}