2021-07-29 18:51:15 +00:00
|
|
|
package mongo
|
2021-07-11 21:19:37 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2021-07-19 14:24:33 +00:00
|
|
|
"os"
|
2021-07-11 21:19:37 +00:00
|
|
|
"time"
|
|
|
|
|
2021-07-19 14:24:33 +00:00
|
|
|
"gitlab.com/gaming0skar123/go/pingbot/common"
|
2021-07-11 21:19:37 +00:00
|
|
|
"gitlab.com/gaming0skar123/go/pingbot/config"
|
|
|
|
"go.mongodb.org/mongo-driver/mongo"
|
|
|
|
"go.mongodb.org/mongo-driver/mongo/options"
|
|
|
|
"go.mongodb.org/mongo-driver/mongo/readpref"
|
|
|
|
)
|
|
|
|
|
2021-07-22 08:23:49 +00:00
|
|
|
var Client mongo.Client
|
|
|
|
var Coll *mongo.Collection
|
2021-07-11 21:19:37 +00:00
|
|
|
|
2021-07-24 09:50:17 +00:00
|
|
|
func Connect(retry ...int8) {
|
|
|
|
if len(retry) == 0 {
|
|
|
|
retry = append(retry, 0)
|
|
|
|
}
|
|
|
|
|
|
|
|
if retry[0] == 2 {
|
|
|
|
os.Exit(1)
|
|
|
|
}
|
|
|
|
|
2021-07-11 21:19:37 +00:00
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
|
|
|
defer cancel()
|
|
|
|
|
|
|
|
Client, err := mongo.Connect(ctx, options.Client().ApplyURI(config.Mongo_URI))
|
2021-07-22 08:23:49 +00:00
|
|
|
if common.CheckErr(err, "connect to db") {
|
2021-07-24 09:50:17 +00:00
|
|
|
time.Sleep(2 * time.Second)
|
|
|
|
Connect(retry[0] + 1)
|
|
|
|
|
|
|
|
return
|
2021-07-11 21:19:37 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
err = Client.Ping(ctx, readpref.Primary())
|
2021-07-22 08:23:49 +00:00
|
|
|
if common.CheckErr(err, "ping db") {
|
2021-07-24 09:50:17 +00:00
|
|
|
time.Sleep(2 * time.Second)
|
|
|
|
Connect(retry[0] + 1)
|
|
|
|
|
|
|
|
return
|
2021-07-11 21:19:37 +00:00
|
|
|
}
|
|
|
|
|
2021-07-22 08:23:49 +00:00
|
|
|
Coll = Client.Database(config.Mongo_DB).Collection(config.Mongo_Collection)
|
2021-07-11 21:19:37 +00:00
|
|
|
}
|