mongodb - 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)
}
解决方案
两者都不。您的上下文应该是请求范围的(对于您的应用程序中的任何“请求”含义),并将调用链传递给每个函数。
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.
}
推荐阅读
- reactjs - How to check the object value in enzyme jest test case
- javascript - Updating an array in angular 4 after adding an element with splice?
- c# - 为什么我的 !ban 命令不起作用(找不到用户)DISCORD.NET / C#
- javascript - if-else 语句在 javascript/html 中不起作用
- python - 从一个 Socket 接收两个函数
- python - 在python中使用正则表达式获取特定文本的左右文本
- r - 未找到函数中的 R 对象
- java - 使用正则表达式查找 Json 值:匹配字符串,然后是任意数量的字符,然后是第二个匹配字符串之后的值
- java - Android/Java:如何从 Canvas 中提取位图?
- python - 如何在 Linux Ubuntu 16.04 中使用 Pip3 安装 Python 3.6 模块?