Go Go

gin 框架 context copy

2021-08-02  本文已影响0人  wuhan_goer

gin框架提供了context copy方法,

什么时候用copy

如果使用新的goroutine的时候需要使用copy方法,因为context不是线程安全的,所以这种场景下需要使用copy,
可以看出copy时handlers,ResponseWriter 都为nil,返回和处理请求的还是主线程去执行。

// 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
}
上一篇 下一篇

猜你喜欢

热点阅读