/
odm.go
47 lines (40 loc) · 1.18 KB
/
odm.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package mongo
import (
"context"
"github.com/klovercloud-ci-cd/event-bank/config"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"log"
"sync"
)
type dmManager struct {
Ctx context.Context
Db *mongo.Database
}
var singletonDmManager *dmManager
var onceDmManager sync.Once
// GetDmManager returns dmManager
func GetDmManager() *dmManager {
onceDmManager.Do(func() {
log.Println("[INFO] Starting Initializing Singleton DB Manager")
singletonDmManager = &dmManager{}
singletonDmManager.initConnection()
})
return singletonDmManager
}
func (dm *dmManager) initConnection() {
// Base context.
log.Println(config.DatabaseConnectionString)
ctx := context.Background()
dm.Ctx = ctx
clientOpts := options.Client().ApplyURI(config.DatabaseConnectionString)
//clientOpts := options.Client().ApplyURI("mongodb+srv://MyDataBase:MongoDBDatabase@harun.wzryz.mongodb.net/<dbname>?retryWrites=true&w=majority")
client, err := mongo.Connect(ctx, clientOpts)
if err != nil {
log.Println("[ERROR] DB Connection error:", err.Error())
return
}
db := client.Database(config.DatabaseName)
dm.Db = db
log.Println("[INFO] Initialized Singleton DB Manager")
}