gin框架提供了context copy方法胜蛉,
什么時候用copy
如果使用新的goroutine的時候需要使用copy方法挠进,因為context不是線程安全的孤紧,所以這種場景下需要使用copy闻蛀,
可以看出copy時handlers,ResponseWriter 都為nil酱畅,返回和處理請求的還是主線程去執(zhí)行案怯。
// 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
}