-
Notifications
You must be signed in to change notification settings - Fork 2
/
connection.go
35 lines (31 loc) · 917 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
package mongotest
import (
"context"
"time"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
func connect(ctx context.Context) (context.Context, *mongo.Client, context.CancelFunc, error) {
client, err := mongo.NewClient(options.Client().ApplyURI(conf.URL))
if err != nil {
return ctx, nil, nil, err
}
ctx, cancel := context.WithTimeout(ctx, time.Duration(conf.Timeout)*time.Second)
err = client.Connect(ctx)
if err != nil {
cancel()
return ctx, nil, nil, err
}
return ctx, client, func() {
client.Disconnect(ctx)
cancel()
}, nil
}
func connectCollection(ctx context.Context, collName string) (context.Context, *mongo.Collection, context.CancelFunc, error) {
ctx, client, cancel, err := connect(ctx)
if err != nil {
return ctx, nil, cancel, err
}
collection := client.Database(conf.Database).Collection(collName)
return ctx, collection, cancel, err
}