-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmongo_service.go
50 lines (40 loc) · 1.11 KB
/
mongo_service.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
package gohoa
import (
"context"
"log"
"time"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type DBService struct {
client *mongo.Client
mailboxDB *mongo.Database
collection *mongo.Collection
}
func createDBService(collectionName string) DBService {
config := GetConfig()
uri := config.MongoDBUrl
dbName := config.MongoDBName
uriShort := uri[40:]
log.Printf(" *--* Connecting to MongoDB: uri [%s]\n", uriShort)
log.Printf(" *--* Connecting to MongoDB: dbname [%s]\n", dbName)
ml := DBService{}
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
options.Client().ApplyURI(uri)
client, err := mongo.Connect(ctx, options.Client().ApplyURI(uri))
if err != nil {
log.Println(" !--! Error connecting to MongoDB: ", err)
}
ml.client = client
//quick ping
err = ml.client.Ping(ctx, nil)
if err != nil {
log.Println(" !--! Error pinging MongoDB: ", err)
} else {
log.Println(" *--* Connected to MongoDB")
}
ml.mailboxDB = ml.client.Database(dbName)
ml.collection = ml.mailboxDB.Collection(collectionName)
return ml
}