加入网络层
This commit is contained in:
@@ -1,77 +0,0 @@
|
||||
package mongo
|
||||
|
||||
import (
|
||||
commonConfig "common/config"
|
||||
"common/log"
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"fmt"
|
||||
"go.mongodb.org/mongo-driver/event"
|
||||
"go.mongodb.org/mongo-driver/mongo"
|
||||
"go.mongodb.org/mongo-driver/mongo/options"
|
||||
"io/ioutil"
|
||||
)
|
||||
|
||||
var (
|
||||
MDB *mongo.Client
|
||||
DefaultDB *mongo.Database
|
||||
ChatDB *mongo.Database
|
||||
ErrNoDocuments = mongo.ErrNoDocuments
|
||||
)
|
||||
|
||||
func Init(cfg *commonConfig.MongoConfig) error {
|
||||
dialect := ""
|
||||
if len(cfg.User) > 0 && len(cfg.Password) > 0 {
|
||||
dialect = fmt.Sprintf("mongodb://%s:%s@%s:%d/admin?appname=MongoDB", cfg.User, cfg.Password, cfg.Host, cfg.Port)
|
||||
} else {
|
||||
dialect = fmt.Sprintf("mongodb://%s:%d/admin?readPreference=primary&appname=MongoDB&ssl=false", cfg.Host, cfg.Port)
|
||||
}
|
||||
var clientOptions *options.ClientOptions
|
||||
if len(cfg.SSLCaFile) > 0 {
|
||||
data, err := ioutil.ReadFile(cfg.SSLCaFile)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
dialect += "&ssl=true"
|
||||
roots := x509.NewCertPool()
|
||||
roots.AppendCertsFromPEM(data)
|
||||
clientOptions = options.Client().ApplyURI(dialect).SetTLSConfig(&tls.Config{
|
||||
RootCAs: roots,
|
||||
//InsecureSkipVerify: true,
|
||||
}).SetRetryWrites(false)
|
||||
} else {
|
||||
dialect += "&ssl=false"
|
||||
clientOptions = options.Client().ApplyURI(dialect).SetRetryWrites(false)
|
||||
}
|
||||
monitor := &event.CommandMonitor{
|
||||
Started: func(ctx context.Context, startedEvent *event.CommandStartedEvent) {
|
||||
log.Infof("mongoDB Command started %v %v", startedEvent.CommandName, startedEvent.Command.String())
|
||||
},
|
||||
Failed: func(ctx context.Context, failedEvent *event.CommandFailedEvent) {
|
||||
log.Errorf("mongoDB Command error %v %v", failedEvent.CommandName, failedEvent.Failure)
|
||||
},
|
||||
}
|
||||
clientOptions.SetMonitor(monitor)
|
||||
client, err := mongo.Connect(context.Background(), clientOptions)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = client.Ping(context.Background(), nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
MDB = client
|
||||
DefaultDB = MDB.Database("ecosmos")
|
||||
ChatDB = MDB.Database("ecosmos_chat")
|
||||
return nil
|
||||
}
|
||||
|
||||
func Close() error {
|
||||
if MDB != nil {
|
||||
return MDB.Disconnect(context.Background())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user