首页 > 解决方案 > Go Context 应该如何声明?

问题描述

假设我有一个修改数据库的文件,函数应该共享一个上下文还是每个函数都有自己的上下文?

共享上下文

var (
    ctx = context.Background()
)

func test1() {
    res, err := Collection.InsertOne(ctx, data)
}

func test2() {
    res, err := Collection.InsertOne(ctx, data)
}

还是应该这样?

   func test1() {
        res, err := Collection.InsertOne(context.Background(), data)
    }
    
    func test2() {
        res, err := Collection.InsertOne(context.Background(), data)
    }

标签: mongodbgo

解决方案


两者都不。您的上下文应该是请求范围的(对于您的应用程序中的任何“请求”含义),并将调用链传递给每个函数。

func test1(ctx context.Context) {
    res, err := Collection.InsertOne(ctx, data)
}

func test2(ctx context.Context) {
    res, err := Collection.InsertOne(ctx, data)
}

如果您正在构建 Web 服务器,如注释中所示,您通常会从处理程序中的 HTTP 请求中获取上下文:

func myHandler(w http.ResponseWriter, r *http.Request) {
    ctx := r.Context()
    // now pass ctx to any fuction that needs it. This way, if the HTTP
    // client/browser cancels the request, your downstream functions will
    // be able to abort immediately, without wasting time finishing their
    // work.
}

推荐阅读