-
Notifications
You must be signed in to change notification settings - Fork 18
/
init.go
44 lines (34 loc) · 899 Bytes
/
init.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
package db
import (
"fmt"
"github.com/gogf/gf/v2/os/gctx"
"github.com/iimeta/fastapi/internal/config"
"github.com/iimeta/fastapi/utility/logger"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
)
var (
client *mongo.Client
DefaultDatabase string
)
func init() {
ctx := gctx.New()
var err error
uri, err := config.Get(ctx, "mongodb.uri")
if err != nil {
logger.Error(ctx, err)
}
if client, err = mongo.Connect(ctx, options.Client().ApplyURI(uri.String())); err != nil {
panic(err)
}
if err = client.Ping(ctx, readpref.Primary()); err != nil {
panic(fmt.Sprint("MongoDB", err))
}
logger.Info(ctx, "MongoDB Successfully connected and pinged.")
database, err := config.Get(ctx, "mongodb.database")
if err != nil {
logger.Error(ctx, err)
}
DefaultDatabase = database.String()
}