瀏覽代碼

fix:mongo地址兼容

Roc 11 月之前
父節點
當前提交
56fe5c7c65
共有 2 個文件被更改,包括 14 次插入19 次删除
  1. 6 6
      config/config.go
  2. 8 13
      init_serve/mongo.go

+ 6 - 6
config/config.go

@@ -92,10 +92,10 @@ type EsClient struct {
 // Mongo
 // @Description: mongo配置
 type Mongo struct {
-	Host       string `mapstructure:"host" json:"host" yaml:"host" description:"mongo地址"`
-	Port       int    `mapstructure:"port" json:"port" yaml:"port" description:"mongo端口"`
-	AuthSource string `mapstructure:"auth-source" json:"auth-source" yaml:"auth-source" description:"认证数据库"`
-	Database   string `mapstructure:"database" json:"database" yaml:"database" description:"默认数据库"`
-	Username   string `mapstructure:"username" json:"username" yaml:"username" description:"用户名"`
-	Password   string `mapstructure:"password" json:"password" yaml:"password" description:"密码"`
+	Url           string `mapstructure:"url" json:"url" yaml:"url" description:"mongo地址url"`
+	AuthMechanism string `mapstructure:"auth_mechanism" json:"auth_mechanism" yaml:"auth_mechanism" description:"鉴权方式"`
+	AuthSource    string `mapstructure:"auth-source" json:"auth-source" yaml:"auth-source" description:"认证数据库"`
+	Database      string `mapstructure:"database" json:"database" yaml:"database" description:"默认数据库"`
+	Username      string `mapstructure:"username" json:"username" yaml:"username" description:"用户名"`
+	Password      string `mapstructure:"password" json:"password" yaml:"password" description:"密码"`
 }

+ 8 - 13
init_serve/mongo.go

@@ -2,7 +2,6 @@ package init_serve
 
 import (
 	"context"
-	"fmt"
 	"github.com/qiniu/qmgo"
 	"github.com/qiniu/qmgo/options"
 	"go.mongodb.org/mongo-driver/bson"
@@ -76,20 +75,16 @@ func MgoNewClient() *qmgo.Client {
 
 	//mongodb+srv://myDatabaseUser:D1fficultP%40ssw0rd@mongodb0.example.com/?authSource=admin&replicaSet=myRepl
 
-	var mongoUrl string
-	if mgoConfig.Password != "" {
-		mongoUrl = fmt.Sprintf("mongodb://%s:%s@%s:%d", mgoConfig.Username, mgoConfig.Password, mgoConfig.Host, mgoConfig.Port)
-
-		if mgoConfig.AuthSource != `` {
-			mongoUrl += mongoUrl + "?&authSource=" + mgoConfig.AuthSource
-		}
-	} else {
-		mongoUrl = fmt.Sprintf("mongodb://%s:%d", mgoConfig.Host, mgoConfig.Port)
-	}
-
 	// 创建一个数据库链接
 	client, err := qmgo.NewClient(ctx, &qmgo.Config{
-		Uri:              mongoUrl,
+		Uri: mgoConfig.Url,
+		Auth: &qmgo.Credential{
+			AuthMechanism: mgoConfig.AuthMechanism,
+			AuthSource:    mgoConfig.AuthSource,
+			Username:      mgoConfig.Username,
+			Password:      mgoConfig.Password,
+			//PasswordSet:   false,
+		},
 		Database:         mgoConfig.Database,
 		ConnectTimeoutMS: &ConnectTimeoutMS,
 		SocketTimeoutMS:  &SocketTimeoutMS,