- 有问题:
- gin context 当函数返回后 goroutine 中context的值可能受到影响
1、访问http://127.0.0.1:8080/test/test?a=1 2、连续访问http://127.0.0.1:8080/test/test?a=2 3、正常输出: 1 +++ + 1 ++++ 1 ---------------------- 1 2 ++++ 2 ++++ 2 --------- ------------- 2 2 ========== 2 =============== 1 ======== == 1 =============== //正常 2 ++++ 2 ++++ 2 ------------------ ---- 2 2 ========== 2 =============== 异常输出: 1 ++++ 1 ++++ 1 ---- ------------------ 1 2 ++++ 2 ++++ 2 -------------------- -- 2 2 ========== 2 =============== 2 ++++ 2 ++++ 2 --------- ------------- 2 2 ========== 2 =============== 1 ======== == 2 =============== //异常http://127.0.0.1:8080/test/test?a=1结果返回从上下文中取出a=2 2 ++ ++ 2 ++++ 2 ---------------------- 2 2 ========== 2 ======= ========
如何重现
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"time"
)
func main() {
gin.SetMode("debug")
r := gin.New()
r.Use(func(ctx *gin.Context) {
ctx.Request = ctx.Request.WithContext(ctx)
ctx.Set("a", ctx.Query("a"))
value, _ := ctx.Get("a")
fmt.Println(ctx.Query("a"), "++++", value, "++++")
})
group := r.Group("/test")
group.GET("/test", func(ctx *gin.Context) {
go func(c *gin.Context) {
//c := &gin.Context{} //重新定以后恢复正常
//*c = *ctx
a := c.Query("a")
fmt.Println(a, "----------------------", c.Value("a"))
if a=="1"{
time.Sleep(3*time.Second)
}
fmt.Println(a, "==========", c.Value("a"), "===============") //此处输出可能异常
}(ctx)
//主函数不退出正常
//time.Sleep
})
url := "0.0.0.0:8080"
r.Run(url)
}
go 1.17.3 windows gin 1.8.1