You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
52 lines
1.0 KiB
Go
52 lines
1.0 KiB
Go
package dbhelper
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"mygo/conf"
|
|
"time"
|
|
|
|
"github.com/fatih/color"
|
|
"go.mongodb.org/mongo-driver/mongo"
|
|
"go.mongodb.org/mongo-driver/mongo/options"
|
|
)
|
|
|
|
var client *mongo.Client
|
|
|
|
func init() {
|
|
color.Green("init mongodb")
|
|
color.Yellow("mongo addr = %v", conf.GetMongoAddr())
|
|
// Set client options
|
|
clientOptions := options.Client().ApplyURI(conf.GetMongoAddr())
|
|
|
|
var err error
|
|
client, err = mongo.Connect(context.TODO(), clientOptions)
|
|
color.Yellow("Connect err = %v", err)
|
|
if err != nil {
|
|
panic("Connect error " + err.Error())
|
|
}
|
|
|
|
go func() {
|
|
color.Green("Check the connection")
|
|
// Check the connection
|
|
for {
|
|
err := client.Ping(context.TODO(), nil)
|
|
if err != nil {
|
|
panic("Ping error " + err.Error())
|
|
}
|
|
time.Sleep(time.Duration(10) * time.Second)
|
|
}
|
|
}()
|
|
|
|
fmt.Println("Connected to MongoDB!")
|
|
}
|
|
|
|
func GetMongoClient() *mongo.Client {
|
|
return client
|
|
}
|
|
|
|
func GetMongoCollection(collection string) *mongo.Collection {
|
|
col := client.Database("leshusanguo").Collection(collection)
|
|
return col
|
|
}
|