-
Notifications
You must be signed in to change notification settings - Fork 0
/
mongo.go
37 lines (31 loc) · 929 Bytes
/
mongo.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
35
36
37
package models
import (
"context"
"os"
"sync"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
/* Used to create a singleton object of MongoDB client.
Initialized and exposed through GetMongoClient().*/
var clientInstance *mongo.Client
//Used during creation of singleton client object in GetMongoClient().
var clientInstanceError error
//Used to execute client creation procedure only once.
var mongoOnce sync.Once
func GetMongoClient() (*mongo.Client, error) {
//Perform connection creation operation only once.
mongoOnce.Do(func() {
clientOptions := options.Client().ApplyURI(os.Getenv("MONGO"))
client, err := mongo.Connect(context.TODO(), clientOptions)
if err != nil {
clientInstanceError = err
}
err = client.Ping(context.TODO(), nil)
if err != nil {
clientInstanceError = err
}
clientInstance = client
})
return clientInstance, clientInstanceError
}