-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatastore.go
34 lines (27 loc) · 843 Bytes
/
datastore.go
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
// Create the master session/connection
package main
import (
"context"
"time"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
// CreateClient creates a connection, using a given connection string
func CreateClient(ctx context.Context, uri string, retry int32) (*mongo.Client, error) {
conn, err := mongo.Connect(ctx, options.Client().ApplyURI(uri))
// 'Pinging' the connection to check it's correct and that the datastore is
// available.
if err := conn.Ping(ctx, nil); err != nil {
// Basic retry logic
if retry >= 3 {
// If it exceeds three retries, we let the error bubble upwards to
// be handled.
return nil, err
}
retry = retry + 1
time.Sleep(time.Second * 2)
// Calling itself again if it can't connect
return CreateClient(ctx, uri, retry)
}
return conn, err
}