Skip to content

decode: do not split charset decoding across the first read - #535

Merged
imroc merged 1 commit into
imroc:masterfrom
AshSgDe29071999:fix/autodecode-split-multibyte
Sep 6, 2026
Merged

imroc merged 1 commit into
imroc:masterfrom
AshSgDe29071999:fix/autodecode-split-multibyte

Conversation

@AshSgDe29071999

Copy link
Copy Markdown
Contributor

Fixes #525.

When the charset is only declared in an HTML <meta> tag, autoDecodeReadCloser.peekRead decoded the first body chunk with Decoder.Bytes and the remainder with Decoder.Reader. Decoder.Bytes treats its input as a complete sequence, so a multi-byte character that straddles that first read (512 bytes for io.ReadAll) is replaced and the leftover trailing byte then starts the streaming decoder mid-character.

The sniffing read is now replayed through the same decoder as the rest of the body via io.MultiReader, which is the approach suggested on the issue. A regression test places GBK 中国 across the 512-byte boundary and checks that the decoded body still contains 中国.

autoDecodeReadCloser peeked the first chunk with Decoder.Bytes and
decoded the remainder with Decoder.Reader. A multi-byte character
that straddled that boundary was treated as a complete input, so
HTML meta charset sniffing could corrupt the body.

Replay the first chunk through the same decoder stream.

Fixes imroc#525
@imroc
imroc merged commit 4c03790 into imroc:master Sep 6, 2026
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.

autoDecodeReadCloser 在首次读取边界拆分多字节字符时会损坏正文

2 participants