Skip to content

middleware: fix httpFancyWriter.ReadFrom double-counting bytes with Tee#1085

Open
alliasgher wants to merge 1 commit intogo-chi:masterfrom
alliasgher:fix-httpfancywriter-readfrom-double-count
Open

middleware: fix httpFancyWriter.ReadFrom double-counting bytes with Tee#1085
alliasgher wants to merge 1 commit intogo-chi:masterfrom
alliasgher:fix-httpfancywriter-readfrom-double-count

Conversation

@alliasgher
Copy link
Copy Markdown

Summary

httpFancyWriter.ReadFrom in middleware/wrap_writer.go double-counted BytesWritten() when a Tee writer was set.

When tee != nil, the code called io.Copy(&f.basicWriter, r), which routes every write through basicWriter.Write. Write already increments basicWriter.bytes. After the copy returned, the old code then did:

f.basicWriter.bytes += int(n)   // BUG: already counted inside Write

…adding n a second time. The result: BytesWritten() returned exactly twice the actual number of bytes transferred.

Fix

Remove the redundant f.basicWriter.bytes += int(n) line in the tee branch. The non-tee path (which delegates to the underlying ReaderFrom, bypassing Write) is not affected and still needs to add n itself.

Test

Added TestHttpFancyWriterReadFromByteCountWithTee that reproduces the original bug (it fails before the fix and passes after). The full middleware test suite still passes.

Fixes #1067

When a Tee writer is set, ReadFrom calls io.Copy(&f.basicWriter, r),
which routes each write through basicWriter.Write. Write already
increments basicWriter.bytes, so the line

    f.basicWriter.bytes += int(n)

that followed the io.Copy double-counted every byte, causing
BytesWritten() to return twice the actual value.

Remove the redundant addition. The non-tee path is unaffected because
it delegates to the underlying ResponseWriter's ReaderFrom (bypassing
Write) and must still add n itself.

Fixes go-chi#1067

Signed-off-by: alliasgher <alliasgher123@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

httpFancyWriter.ReadFrom double-counts BytesWritten when Tee is set

1 participant