go 代码报错处理

连接mongodb出现error occurred during connection handshake: auth error: sasl conversation error: unable to authenticate using

连接mongodb出现error occurred during connection handshake: auth error: sasl conversation error: unable to authenticate using mechanism “SCRAM-SHA-1”: (AuthenticationFailed) Authentication failed.

package urls

import (
	"context"
	"errors"
	"fmt"

	log "github/sirupsen/logrus"
	"go.mongodb/mongo-driver/mongo"
	"go.mongodb/mongo-driver/mongo/options"
)

var msg string
// OpenMongo 进行传入ip 端口 密码 账号返回一个连接地址
func OpenMongo(ip string, port int, name, password string) (*mongo.Client, error) {
	applyurl := fmt.Sprintf("mongodb://%s:%d", ip, port)

	credential := options.Credential{
		AuthMechanism: "SCRAM-SHA-256",
		// AuthMechanism: "SCRAM-SHA-1",
		Username:   name,
		Password:   password,
		AuthSource: "admin",
	}
	clientOpts := options.Client().ApplyURI(applyurl).SetAuth(credential).SetConnectTimeout(2 * time.Second).SetSocketTimeout(2 * time.Second)

	ctx := context.Background()

	client, err := mongo.Connect(ctx, clientOpts)
	if err != nil {
		return nil, fmt.Errorf("连接MongoDB失败: %w", err)
	}
	// Ping MongoDB with timeout
	pingCtx, pingCancel := context.WithTimeout(context.Background(), 2*time.Second) // 设置Ping超时时间为2秒
	defer pingCancel()

	if err := client.Ping(pingCtx, nil); err != nil {
		_ = client.Disconnect(ctx)
		return nil, fmt.Errorf("无法ping通MongoDB服务器: %w", err)
	}
	return client, nil
}

发布者:admin,转转请注明出处:http://www.yc00.com/web/1754606219a5181639.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信