fix(util/gconv): gconv unsafe str to bytes - #4600
Merged
Merged
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
The gconv.UnsafeStrToBytes function has been updated to use the Go 1.20+ safe approach, as the previous implementation could cause a panic in certain scenarios.
For example, when an HTTP request header specifies Content-Type: application/x-www-form-urlencoded, but the actual request body contains JSON data, the following code attempts to detect and handle this case:
However, after this assignment, bodyContent ends up with a capacity (cap) of 0. slice operations like [:] perform stricter validation and will panic if the capacity is 0. This causes a panic in functions such as:
The capacity (cap) of the slice returned by directly calling this function is unpredictable, as it depends on the adjacent memory layout. However, within the framework, this causes issues—likely because, starting from Go 1.22, the standard library's parseForm implementation consistently appends a trailing zero byte after the string data in memory.
This PR fix the problem.
gconv unsafe str to bytes 改用 go1.20 后的写法,之前的写法在某些场景下会 panic
例如 http 请求头为
application/x-www-form-urlencoded,实际的 body 为 json,经过解析后
bodyContent的 cap 为 0,由于切片操作[:]会校验 cap 为 0,会直接 panic
直接使用这个函数得到的 cap 会是随机的, 因为跟的内存不确定,但是在框架中有问题,估计是1.22 后标准库parseForm 的时候后面内存固定跟了个 0
该 PR 修复这个问题