Skip to content

Commit dc773a1

Browse files
author
Chris Cho
authored
Docs 13739 fix go connection (#651)
* DOCS-13739: fix go connection snippet
1 parent ff2fdf9 commit dc773a1

File tree

2 files changed

+40
-10
lines changed

2 files changed

+40
-10
lines changed

source/go.txt

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -50,20 +50,12 @@ Connect to MongoDB Atlas
5050

5151
.. include:: /includes/atlas-connect-blurb.rst
5252

53-
.. code-block:: go
54-
55-
import "go.mongodb.org/mongo-driver/mongo"
56-
57-
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
58-
client, err := mongo.Connect(ctx, options.Client().ApplyURI(
59-
"mongodb+srv://<username>:<password>@<cluster-address>/test?w=majority"
60-
))
61-
if err != nil { log.Fatal(err) }
53+
.. literalinclude:: /includes/connection-snippets/go-connection.go
54+
:language: go
6255

6356
See `Usage <https://github.com/mongodb/mongo-go-driver#usage>`__
6457
for more detail.
6558

66-
6759
Compatibility
6860
-------------
6961

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package main
2+
3+
import (
4+
"context"
5+
"fmt"
6+
"log"
7+
"time"
8+
9+
"go.mongodb.org/mongo-driver/mongo"
10+
"go.mongodb.org/mongo-driver/mongo/options"
11+
"go.mongodb.org/mongo-driver/mongo/readpref"
12+
)
13+
14+
func main() {
15+
16+
// Replace the uri string with your MongoDB deployment's connection string.
17+
uri := "mongodb+srv://<username>:<password>@<cluster-address>/test?w=majority"
18+
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
19+
defer cancel()
20+
21+
client, err := mongo.Connect(ctx, options.Client().ApplyURI(uri))
22+
if err != nil {
23+
panic(err)
24+
}
25+
26+
defer func() {
27+
if err = client.Disconnect(ctx); err != nil {
28+
panic(err)
29+
}
30+
}()
31+
32+
// Ping the primary
33+
if err := client.Ping(ctx, readpref.Primary()); err != nil {
34+
panic(err)
35+
}
36+
37+
fmt.Println("Successfully connected and pinged.")
38+
}

0 commit comments

Comments
 (0)