New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
gin/context Copy method comment is confuse #3137
Comments
Panic because c.Writer.ResponseWriter was nil package main
import (
"github.com/gin-gonic/gin"
)
func CreateVulJob(c *gin.Context) {
env := c.Param("env")
if env == "aliyun" {
go doSomething(c)
} else {
go doOtherSomething(c)
}
}
func doSomething(c *gin.Context) {
c.JSON(200, `{"message": "doSomething"}`)
}
func doOtherSomething(c *gin.Context) {
// panic because c.Writer.ResponseWriter was nil
c.JSON(200, `{"message": "doOtherSomething"}`)
}
func main() {
r := gin.Default()
r.GET("/", func(c *gin.Context) {
CreateVulJob(c.Copy())
// c.JSON(200, `{"message": "ok"}`)
})
r.Run(":18080")
} cp.Writer just get its pointer // Copy returns a copy of the current context that can be safely used outside the request's scope.
// This has to be used when the context has to be passed to a goroutine.
func (c *Context) Copy() *Context {
cp := Context{
writermem: c.writermem,
Request: c.Request,
Params: c.Params,
engine: c.engine,
}
cp.writermem.ResponseWriter = nil
cp.Writer = &cp.writermem
cp.index = abortIndex
cp.handlers = nil
cp.Keys = map[string]interface{}{}
for k, v := range c.Keys {
cp.Keys[k] = v
}
paramCopy := make([]Param, len(cp.Params))
copy(paramCopy, cp.Params)
cp.Params = paramCopy
return &cp
} |
I'm getting a similar issue when using |
documentation regarding using go routines as middleware states that "you have to use a read-only copy" of the context. maybe this is why the response writer is nil and is therefore producing the panic |
Facing same issue, anyone find anything for the workaround of this? |
It designed just data copy, not the stream copy. Because if the write stream handle can copy, then the program can't decide when close the stream, so it may cause goroutine leak.
|
Thanks a lot @fengbenming for the help. I'm still a bit new to Go & Gin so learning the ropes.
Using a copy context, throws panic in the GetPostInternal function on a "c.JSON()" binding, as a copy context's writer is NIL. |
Description
the comment say can be safely used outside the request's scope, but it is wrong, it just in the request's scope.
How to reproduce
Expectations
Actual result
Environment
The text was updated successfully, but these errors were encountered: