假设我有一个修改数据库的文件,函数应该共享一个上下文还是每个函数都有自己的上下文?
共享上下文
var (
ctx = context.Background()
)
func test1() {
res, err := Collection.InsertOne(ctx, data)
}
func test2() {
res, err := Collection.InsertOne(ctx, data)
}
Run Code Online (Sandbox Code Playgroud)
或者应该是这样的?
func test1() {
res, err := Collection.InsertOne(context.Background(), data)
}
func test2() {
res, err := Collection.InsertOne(context.Background(), data)
}
Run Code Online (Sandbox Code Playgroud)
两者都不。您的上下文应该是请求范围的(对于您的应用程序中的任何“请求”意味着什么),并将调用链传递给每个函数。
func test1(ctx context.Context) {
res, err := Collection.InsertOne(ctx, data)
}
func test2(ctx context.Context) {
res, err := Collection.InsertOne(ctx, data)
}
Run Code Online (Sandbox Code Playgroud)
如果您正在构建 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.
}
Run Code Online (Sandbox Code Playgroud)