-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmongo.go
More file actions
41 lines (32 loc) · 956 Bytes
/
mongo.go
File metadata and controls
41 lines (32 loc) · 956 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package main
import (
"context"
"fmt"
"time"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
)
func connect(uri string) (*mongo.Client, context.Context, context.CancelFunc, error) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
// mongo.Connect return mongo.Client method
client, err := mongo.Connect(ctx, options.Client().ApplyURI(uri))
return client, ctx, cancel, err
}
// Pings the mongodb
func ping(client *mongo.Client, ctx context.Context) {
if client.Ping(ctx, readpref.Primary()) != nil {
fmt.Println("Not connected to mongodb.")
} else {
fmt.Println("Connected to mongodb.")
}
}
// Closes mongoDB connection and cancel context.
func close(client *mongo.Client, ctx context.Context, cancel context.CancelFunc) {
defer cancel()
defer func() {
if err := client.Disconnect(ctx); err != nil {
panic(err)
}
}()
}