Skip to content
Snippets Groups Projects
mongo-connection.go 1 KiB
Newer Older
  • Learn to ignore specific revisions
  • 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))
    
    		log.Printf("Failed to create client: %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)