Skip to content

Commit 3191cb1

Browse files
author
Chris Cho
authored
DOCS-13739: add defers to the code snippets in the README (#437)
1 parent 20b6cab commit 3191cb1

File tree

1 file changed

+15
-2
lines changed

1 file changed

+15
-2
lines changed

README.md

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ To get started with the driver, import the `mongo` package, create a `mongo.Clie
5151
import (
5252
"go.mongodb.org/mongo-driver/mongo"
5353
"go.mongodb.org/mongo-driver/mongo/options"
54+
"go.mongodb.org/mongo-driver/mongo/readpref"
5455
)
5556

5657
client, err := mongo.NewClient(options.Client().ApplyURI("mongodb://localhost:27017"))
@@ -59,17 +60,29 @@ client, err := mongo.NewClient(options.Client().ApplyURI("mongodb://localhost:27
5960
And connect it to your running MongoDB server:
6061

6162
```go
62-
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
63+
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
64+
defer cancel()
6365
err = client.Connect(ctx)
6466
```
6567

6668
To do this in a single step, you can use the `Connect` function:
6769

6870
```go
69-
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
71+
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
72+
defer cancel()
7073
client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
7174
```
7275

76+
Make sure to defer a call to `Disconnect` after instantiating your client:
77+
78+
```go
79+
defer func() {
80+
if err = client.Disconnect(ctx); err != nil {
81+
panic(err)
82+
}
83+
}()
84+
```
85+
7386
Calling `Connect` does not block for server discovery. If you wish to know if a MongoDB server has been found and connected to,
7487
use the `Ping` method:
7588

0 commit comments

Comments
 (0)