Skip to content

Instantly share code, notes, and snippets.

@radhakishans1378
Last active May 4, 2024 16:39
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save radhakishans1378/a90eaf230e6409f239a81dc0b2246fd0 to your computer and use it in GitHub Desktop.
Save radhakishans1378/a90eaf230e6409f239a81dc0b2246fd0 to your computer and use it in GitHub Desktop.
dalhelper
package connectionhelper
import (
"context"
"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
//I have used below constants just to hold required database config's.
const (
CONNECTIONSTRING = "mongodb://localhost:27017"
DB = "db_issue_manager"
ISSUES = "col_issues"
)
//GetMongoClient - Return mongodb connection to work with
func GetMongoClient() (*mongo.Client, error) {
//Perform connection creation operation only once.
mongoOnce.Do(func() {
// Set client options
clientOptions := options.Client().ApplyURI(CONNECTIONSTRING)
// Connect to MongoDB
client, err := mongo.Connect(context.TODO(), clientOptions)
if err != nil {
clientInstanceError = err
}
// Check the connection
err = client.Ping(context.TODO(), nil)
if err != nil {
clientInstanceError = err
}
clientInstance = client
})
return clientInstance, clientInstanceError
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment