-
Notifications
You must be signed in to change notification settings - Fork 0
/
connect.go
49 lines (42 loc) · 1.1 KB
/
connect.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
// Package mongos
// author gmfan
// date 2023/2/28
package mongos
import (
"context"
"github.com/tkgfan/got/core/env"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"time"
)
var db *mongo.Database
func DB() *mongo.Database {
return db
}
// InitDatabase 初始化 Mongo
func InitDatabase(ctx context.Context, c Conf) (err error) {
client, err := mongo.Connect(ctx, options.
Client().
ApplyURI(c.URI).
SetMaxConnecting(uint64(c.MaxPoolSize)).
SetConnectTimeout(time.Duration(c.MaxTimeout)*time.Second))
if err != nil {
return
}
db = client.Database(c.DB)
return nil
}
type Conf struct {
URI string
DB string
MaxPoolSize int64
// 单位秒
MaxTimeout int64
}
// LoadEnvConf 加载环境变量中的 Mongo 配置,must 设置为环境变量中是否必须存在
func LoadEnvConf(c *Conf, must bool) {
env.LoadStr(&c.URI, "MONGO_URI", must)
env.LoadStr(&c.DB, "MONGO_DB", must)
env.LoadInt64(&c.MaxPoolSize, "MONGO_MAX_POOL_SIZE", must)
env.LoadInt64(&c.MaxTimeout, "MONGO_MAX_TIME_OUT", must)
}