-
-
Save radhakishans1378/a90eaf230e6409f239a81dc0b2246fd0 to your computer and use it in GitHub Desktop.
dalhelper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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