mirror of
https://gitlab.52pay.top/go/easygoadmin.git
synced 2025-09-27 03:48:27 +08:00
43 lines
1.0 KiB
Go
43 lines
1.0 KiB
Go
package utils
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"github.com/sirupsen/logrus"
|
|
"gitlab.52pay.top/go/easygoadmin/library/cfg"
|
|
"go.mongodb.org/mongo-driver/mongo"
|
|
"go.mongodb.org/mongo-driver/mongo/options"
|
|
)
|
|
|
|
var Mongodb *mongo.Database
|
|
|
|
func init() {
|
|
logrus.Info("初始化并连接mongodb")
|
|
config := cfg.Instance()
|
|
uri := fmt.Sprintf("mongodb://%s:%s@%s:%d",
|
|
config.Mongodb.User,
|
|
config.Mongodb.Password,
|
|
config.Mongodb.Host,
|
|
config.Mongodb.Port)
|
|
clientOpt := options.Client().
|
|
ApplyURI(uri)
|
|
cli, err := mongo.Connect(context.Background(), clientOpt)
|
|
if err != nil {
|
|
logrus.Errorf("mongo数据库连接错误:%v", err.Error())
|
|
return
|
|
}
|
|
|
|
// 通过engine.Ping()来进行数据库的连接测试是否可以连接到数据库。
|
|
err = cli.Ping(context.Background(), nil)
|
|
if err == nil {
|
|
logrus.Info("mongo数据库连接成功")
|
|
//关闭连接
|
|
//defer XormDb.Close()
|
|
} else {
|
|
logrus.Errorf("mongo数据库连接错误:%v", err.Error())
|
|
return
|
|
}
|
|
|
|
Mongodb = cli.Database(config.Mongodb.Database)
|
|
}
|