美文网首页Go Go
gin 框架 context copy

gin 框架 context copy

作者: wuhan_goer | 来源:发表于2021-08-02 17:19 被阅读0次

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
}

相关文章

网友评论

    本文标题:gin 框架 context copy

    本文链接:https://www.haomeiwen.com/subject/pndjvltx.html