Closed. This question is
opinion-based。它当前不接受答案。
想改善这个问题吗?更新问题,以便
editing this post用事实和引用来回答。
在6个月前关闭。
Improve this question
mongo-go-driver的所有数据库查询方法都接受上下文:
func (coll *Collection) Find(ctx context.Context, ...)
通常将带有超时的http请求上下文的子代传递给以下查询方法:
ctx, cancel = context.WithTimeout(request.Context()), 5*time.Second)
defer cancel()
cur, err := collection.Find(ctx, ...)
这在Web应用程序的代码库中创建了许多样板。我当时正在考虑创建包装器函数,以在内部创建上下文:
func (db *Database) FindWithContext(filter interface{}) error {
ctx, cancel = context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
return db.Collection.Find(ctx, filter)
}
这是不好的做法吗?上下文是否应该视为http请求的子级,以便在处理程序中确定超时和取消的范围?创建包装函数会否破坏上下文的整个目的?