-
Notifications
You must be signed in to change notification settings - Fork 0
/
mongo.go
40 lines (35 loc) · 871 Bytes
/
mongo.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
package connect
import (
"context"
"fmt"
"strings"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
"github.com/spf13/viper"
)
var (
MongoClient string
mongoUri = []string{
"mongodb://",
viper.GetString("mongodb.server.user"),":",
viper.GetString("mongodb.server.pass"),"@",
viper.GetString("mongodb.server.host"),
"/?maxPollSize=20&w=majority"}
)
func init() {
fmt.Println(mongoUri)
client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(strings.Join(mongoUri,"")))
if err != nil {
panic(err)
}
if err := client.Ping(context.TODO(), readpref.Primary()); err != nil {
panic(err)
}
fmt.Println("Successfully connected and pinged.")
defer func() {
if err = client.Disconnect(context.TODO()); err != nil {
panic(err)
}
}()
}