forked from coze-cloud/clerk
/
connection.go
51 lines (43 loc) 路 996 Bytes
/
connection.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"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
)
type Connection struct {
ctx context.Context
config Config
client *mongo.Client
}
func NewConnection(
ctx context.Context,
config Config,
) (*Connection, error) {
opts := options.Client().
SetConnectTimeout(config.Timeout).
SetServerSelectionTimeout(config.Timeout).
SetSocketTimeout(config.Timeout).
SetTimeout(config.Timeout).
ApplyURI(string(config.Host))
client, err := mongo.Connect(ctx, opts)
if err != nil {
return nil, err
}
pingCtx, pingCancel := config.GetContext(ctx)
defer pingCancel()
if err = client.Ping(pingCtx, readpref.Primary()); err != nil {
return nil, err
}
return &Connection{
ctx: ctx,
config: config,
client: client,
}, nil
}
func (c *Connection) Close(handler func(err error)) {
err := c.client.Disconnect(c.ctx)
if handler != nil {
handler(err)
}
}