dreamfactory_cmd/cmd/v2/lib/common/mongo.go
2023-06-09 21:58:02 +08:00

58 lines
1.4 KiB
Go

package common
import (
"context"
"fmt"
os_storage "go_dreamfactory/cmd/v2/lib/storage"
"github.com/sirupsen/logrus"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type MogoTool struct {
conf *os_storage.Config
storage os_storage.Storage
db *mongo.Database
client *mongo.Client
}
func NewMogoTool() *MogoTool {
this := &MogoTool{}
this.storage, _ = os_storage.NewOSStorage()
var err error
this.conf, err = this.storage.LoadConfig()
if err != nil {
logrus.Error(err)
}
return this
}
func (this *MogoTool) OpenConn() {
if this.conf.MgoDB == nil {
return
}
var option *options.ClientOptions
if (this.conf.MgoDB.User == "" && this.conf.MgoDB.Password == "") &&
this.conf.MgoDB.Host != "" && this.conf.MgoDB.Port != 0 && this.conf.MgoDB.Database != "" {
option = options.Client().ApplyURI(fmt.Sprintf("mongodb://%s:%d", this.conf.MgoDB.Host, this.conf.MgoDB.Port))
} else {
option = options.Client().ApplyURI(fmt.Sprintf("mongodb://%s:%s@%s:%d", this.conf.MgoDB.User, this.conf.MgoDB.Password,
this.conf.MgoDB.Host, this.conf.MgoDB.Port))
}
client, err := mongo.Connect(context.TODO(), option)
if err != nil {
logrus.Error(err)
return
}
if err2 := client.Ping(context.TODO(), nil); err2 != nil {
logrus.Error("Mongo连接失败", err2)
return
}
this.db = client.Database(this.conf.MgoDB.Database)
logrus.Info("mongo connect successful")
}