gin icon indicating copy to clipboard operation
gin copied to clipboard

c.ClientIP() is incorrect under goroutine

Open leeqvip opened this issue 1 year ago • 2 comments

  • 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

leeqvip avatar Jul 07 '22 12:07 leeqvip

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.

eleven26 avatar Jul 10 '22 13:07 eleven26

@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)
}

timandy avatar Jul 11 '22 15:07 timandy