-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.go
47 lines (40 loc) · 831 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
43
44
45
46
47
package main
import (
"context"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"sync"
"time"
)
var client *mongo.Client
func InitDB() error {
c, err := mongo.NewClient(options.Client().ApplyURI(config.DB.MongoUri))
if err != nil {
return err
}
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
err = c.Connect(ctx)
if err != nil {
return err
}
client = c
return nil
}
var onceDB sync.Once
var db *mongo.Database
func DB() *mongo.Database {
onceDB.Do(func() {
db = client.Database(config.DB.DBName)
})
return db
}
var cols = new(sync.Map)
func C(collection string) *mongo.Collection {
if c, exist := cols.Load(collection); exist {
return c.(*mongo.Collection)
} else {
c := DB().Collection(collection)
cols.Store(collection, c)
return c
}
}