Newer
Older
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, error) {
mongoConnection := config.DatabaseConnection
ctx, cancel := context.WithTimeout(context.Background(), connectTimeout*time.Second)
client, err := mongo.Connect(ctx, options.Client().ApplyURI(mongoConnection))
if err != nil {
log.Printf("Failed to create client: %v", err)
return nil, ctx, cancel, 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 nil, ctx, cancel, err
}
return client, ctx, cancel, nil