-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.go
42 lines (33 loc) · 810 Bytes
/
db.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
package db
import (
"context"
"fmt"
"log"
"os"
"time"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
)
//Client is a mongo client
var Client *mongo.Client
//ConnectDb connnect to the databse
func ConnectDb() {
var err error
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
Client, err = mongo.Connect(ctx, options.Client().ApplyURI(os.Getenv("MONGO_URI")))
if err != nil {
log.Println("Error", err)
}
fmt.Println("Connected to MongoDB")
// defer func() {
// if err = Client.Disconnect(ctx); err != nil {
// log.Println("Error: ", err)
// }
// }()
t := Client.Ping(context.TODO(), readpref.Primary())
if t == nil {
fmt.Println("Connected To Client")
}
}