2021-07-29 18:51:15 +00:00
|
|
|
package mongo
|
2021-07-11 21:19:37 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"time"
|
|
|
|
|
2021-08-12 19:26:54 +00:00
|
|
|
"github.com/MedzikUser/go-utils/common"
|
2021-11-10 13:38:54 +00:00
|
|
|
"github.com/medzikuser/go-pingbot/config"
|
2021-07-11 21:19:37 +00:00
|
|
|
"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-09-05 10:50:41 +00:00
|
|
|
func Connect() error {
|
|
|
|
return common.Retry(5, 2*time.Second, func() error {
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
|
|
|
defer cancel()
|
2021-07-24 09:50:17 +00:00
|
|
|
|
2021-09-05 10:50:41 +00:00
|
|
|
Client, err := mongo.Connect(ctx, options.Client().ApplyURI(config.Mongo_URI))
|
2021-11-07 19:19:06 +00:00
|
|
|
if err != nil {
|
|
|
|
common.Log.Error("connect to db", err)
|
|
|
|
|
2021-09-05 10:50:41 +00:00
|
|
|
time.Sleep(2 * time.Second)
|
2021-07-24 09:50:17 +00:00
|
|
|
|
2021-09-05 10:50:41 +00:00
|
|
|
return err
|
|
|
|
}
|
2021-07-11 21:19:37 +00:00
|
|
|
|
2021-09-05 10:50:41 +00:00
|
|
|
err = Client.Ping(ctx, readpref.Primary())
|
2021-11-07 19:19:06 +00:00
|
|
|
if err != nil {
|
|
|
|
common.Log.Error("ping db", err)
|
|
|
|
|
2021-09-05 10:50:41 +00:00
|
|
|
time.Sleep(2 * time.Second)
|
2021-07-24 09:50:17 +00:00
|
|
|
|
2021-09-05 10:50:41 +00:00
|
|
|
return err
|
|
|
|
}
|
2021-07-11 21:19:37 +00:00
|
|
|
|
2021-09-08 20:01:58 +00:00
|
|
|
Coll = Client.Database(config.Toml.MongoDB.Database).Collection(config.Toml.MongoDB.Collection)
|
2021-07-24 09:50:17 +00:00
|
|
|
|
2021-09-05 10:50:41 +00:00
|
|
|
return nil
|
|
|
|
})
|
2021-07-11 21:19:37 +00:00
|
|
|
}
|