Golang driver context

ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
var results bson.M
err := fsFiles.FindOne(ctx, bson.M{}).Decode(&results)

I can see that in mongo-go-driver, we usually put a withTimeout context in the database query. I want to know if that’s necessary to each and every database query.

As shown in the above code, why the “cancel” value being disregarded. Isn’t calling a defer cancel() be better?

If I’m using the “gin” framework, can I just put the gin context into the query context and not specifying a “withTimeout context”?

Hi @Jason_W,

Every driver call that may block requires a context to be passed in. If you’re willing to let the call block for as long as necessary, you can use context.Background() for this. If you want to have a specific timeout for the entire call, you can use WithTimeout as the examples do. You can also use context.WithCancel if you want to provide a cancellable context with no timeout.

Thanks for pointing out the disregarded context.CancelFunc return value. I’ve opened Add deferred context cancellations to README examples by divjotarora · Pull Request #441 · mongodb/mongo-go-driver · GitHub to fix this in our README examples.

– Divjot

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.