Skip to content

Commit 2ff9f87

Browse files
author
Divjot Arora
authored
Add deferred context cancellations to README examples (#441)
1 parent 283326f commit 2ff9f87

File tree

1 file changed

+8
-4
lines changed

1 file changed

+8
-4
lines changed

README.md

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,8 @@ Calling `Connect` does not block for server discovery. If you wish to know if a
8787
use the `Ping` method:
8888

8989
```go
90-
ctx, _ = context.WithTimeout(context.Background(), 2*time.Second)
90+
ctx, cancel = context.WithTimeout(context.Background(), 2*time.Second)
91+
defer cancel()
9192
err = client.Ping(ctx, readpref.Primary())
9293
```
9394

@@ -100,15 +101,17 @@ collection := client.Database("testing").Collection("numbers")
100101
The `Collection` instance can then be used to insert documents:
101102

102103
```go
103-
ctx, _ = context.WithTimeout(context.Background(), 5*time.Second)
104+
ctx, cancel = context.WithTimeout(context.Background(), 5*time.Second)
105+
defer cancel()
104106
res, err := collection.InsertOne(ctx, bson.M{"name": "pi", "value": 3.14159})
105107
id := res.InsertedID
106108
```
107109

108110
Several query methods return a cursor, which can be used like this:
109111

110112
```go
111-
ctx, _ = context.WithTimeout(context.Background(), 30*time.Second)
113+
ctx, cancel = context.WithTimeout(context.Background(), 30*time.Second)
114+
defer cancel()
112115
cur, err := collection.Find(ctx, bson.D{})
113116
if err != nil { log.Fatal(err) }
114117
defer cur.Close(ctx)
@@ -130,7 +133,8 @@ var result struct {
130133
Value float64
131134
}
132135
filter := bson.M{"name": "pi"}
133-
ctx, _ = context.WithTimeout(context.Background(), 5*time.Second)
136+
ctx, cancel = context.WithTimeout(context.Background(), 5*time.Second)
137+
defer cancel()
134138
err = collection.FindOne(ctx, filter).Decode(&result)
135139
if err != nil {
136140
log.Fatal(err)

0 commit comments

Comments
 (0)