gin
gin copied to clipboard
c.ClientIP() is incorrect under goroutine
- With issues:
- Use the search tool before opening a new issue.
- Please provide source code and commit sha if you found a bug.
- Review existing issues and provide feedback or react to them.
Description
c.ClientIP() is incorrect under goroutine
How to reproduce
func Handler(c *gin.Context){
ip1 := c.ClientIP()
go func(ip1 string) {
ip2 := c.ClientIP()
fmt.Println(ip1, ip2) // Under high concurrency, the two are not equal
}(ip1)
c.JSON(200, nil)
}
Expectations
fmt.Println(ip1, ip2) // Under high concurrency, the two are not equal
In most cases, the two are equal, but under high concurrency, the two are not equal, and the ip is rewritten by other requests
Actual result
Environment
- go version: 1.16
- gin version (or commit ref): v1.7.7
- operating system: centos 7
You should pass context
as first parameter to your goroutine,otherwise, you will get a different context in the goroutine, and the ip will naturally be different,that's what context exists for.
@leeqvip context is pooled object, pass context.Copy as first param.
func Handler(c *gin.Context) {
ip1 := c.ClientIP()
go func(cc *gin.Context) {
ip2 := cc.ClientIP()
fmt.Println(ip1, ip2)
}(c.Copy())
c.JSON(200, nil)
}