连接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条)