所有 mongo-go-driver 的數(shù)據(jù)庫(kù)查詢方法都接受一個(gè)上下文:func (coll *Collection) Find(ctx context.Context, ...)通常將帶有超時(shí)的 http 請(qǐng)求上下文的子項(xiàng)傳遞給這些查詢方法:ctx, cancel = context.WithTimeout(request.Context()), 5*time.Second)defer cancel()cur, err := collection.Find(ctx, ...)這會(huì)在 Web 應(yīng)用程序的代碼庫(kù)中創(chuàng)建大量樣板。我正在考慮創(chuàng)建在內(nèi)部創(chuàng)建上下文的包裝函數(shù):func (db *Database) FindWithContext(filter interface{}) error { ctx, cancel = context.WithTimeout(context.Background(), 5*time.Second) defer cancel() return db.Collection.Find(ctx, filter)}這是一個(gè)不好的做法嗎?上下文是否應(yīng)該是 http 請(qǐng)求的子級(jí),以便超時(shí)和取消在處理程序內(nèi)進(jìn)行?創(chuàng)建包裝函數(shù)會(huì)破壞上下文的全部目的嗎?
mongo-go-driver 上下文包裝函數(shù)
HUH函數(shù)
2022-06-27 14:58:00