Newer
Older
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
42
package database
import (
"context"
"log"
"time"
"code.fbi.h-da.de/danet/gosdn/controller/config"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
const (
// Timeout operations after N seconds
connectTimeout = 5
// DatabaseName is the name of the mongoDB database used.
DatabaseName = "gosdn"
)
// GetMongoConnection Retrieves a client to the MongoDB
func GetMongoConnection() (*mongo.Client, context.Context, context.CancelFunc) {
mongoConnection := config.DatabaseConnection
client, err := mongo.NewClient(options.Client().ApplyURI(mongoConnection))
if err != nil {
log.Printf("Failed to create client: %v", err)
}
ctx, cancel := context.WithTimeout(context.Background(), connectTimeout*time.Second)
err = client.Connect(ctx)
if err != nil {
log.Printf("Failed to connect to cluster: %v", err)
}
// Force a connection to verify our connection string
err = client.Ping(ctx, nil)
if err != nil {
log.Printf("Failed to connect to database: %v\n", err)
}
return client, ctx, cancel
}