Skip to content
Snippets Groups Projects
mongo-connection.go 1.03 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) {
    	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
    }