-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
59 lines (47 loc) · 1.21 KB
/
client.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
52
53
54
55
56
57
58
59
package mongo_connection
import (
"context"
"crypto/tls"
"time"
"github.com/Bezunca/mongo_connection/config"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
var globalClient *mongo.Client = nil
var globalContext context.Context = nil
var globalConfigs *config.MongoConfigs = nil
func New(configs *config.MongoConfigs, tlsConfig *tls.Config) (*mongo.Client, error) {
url, err := configs.Url()
if err != nil {
return nil, err
}
globalConfigs = configs
globalClient, err = mongo.NewClient(
options.Client().
ApplyURI(url).
SetAuth(configs.Credentials()).
SetTLSConfig(tlsConfig),
)
if err != nil {
return nil, err
}
globalContext = context.Background()
if err = globalClient.Connect(globalContext); err != nil {
return nil, err
}
return globalClient, nil
}
func Get() *mongo.Client {
if globalClient == nil {
panic("MongoDB client must be initialized before used!")
}
return globalClient
}
func Close() error {
ctx, cancel := context.WithTimeout(globalContext, 5*time.Second)
defer cancel()
return Get().Disconnect(ctx)
}
func TimeoutContext() (context.Context, context.CancelFunc) {
return context.WithTimeout(globalContext, globalConfigs.Timeout)
}