/
mongo.go
51 lines (38 loc) · 1020 Bytes
/
mongo.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
48
49
50
51
package db
import (
"context"
"log"
"github.com/blackmesadev/black-mesa/structs"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type DB struct {
client *mongo.Client
}
func InitDB() *DB {
db := &DB{client: &mongo.Client{}}
return db
}
func (db *DB) ConnectDB(mongoCfg structs.MongoConfig) {
var err error
creds := options.Credential{}
creds.Username = mongoCfg.Username
creds.Password = mongoCfg.Password
clientOptions := options.Client()
clientOptions.ApplyURI(mongoCfg.ConnectionString)
if mongoCfg.Username != "" && mongoCfg.Password != "" {
clientOptions.SetAuth(creds)
}
db.client, err = mongo.Connect(context.TODO(), clientOptions)
if err != nil {
log.Fatalln("Mongo Connection Failed. Unable to start, ", err)
}
err = db.client.Ping(context.TODO(), nil)
if err != nil {
log.Fatalln("Mongo Connection Failed. Unable to start, ", err)
}
log.Println("Mongo Connected.")
}
func (db *DB) GetMongoClient() *mongo.Client {
return db.client
}