/
mongodb.go
51 lines (43 loc) 路 998 Bytes
/
mongodb.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
51
package mongodb
import (
"context"
"time"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
const (
connectTimeout = 30 * time.Second
maxConnIdleTime = 3 * time.Minute
minPoolSize = 20
maxPoolSize = 300
)
// Config MongoDB config
type Config struct {
URI string
User string
Password string
DB string
}
// NewMongoDBConn Create new MongoDB client
func NewMongoDBConn(ctx context.Context, cfg *Config) (*mongo.Client, error) {
client, err := mongo.NewClient(
options.Client().ApplyURI(cfg.URI).
SetAuth(options.Credential{
Username: cfg.User,
Password: cfg.Password,
}).
SetConnectTimeout(connectTimeout).
SetMaxConnIdleTime(maxConnIdleTime).
SetMinPoolSize(minPoolSize).
SetMaxPoolSize(maxPoolSize))
if err != nil {
return nil, err
}
if err := client.Connect(ctx); err != nil {
return nil, err
}
if err := client.Ping(ctx, nil); err != nil {
return nil, err
}
return client, nil
}