连接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.com/sirupsen/logrus"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
var msg string
func OpenMongo(ip string, port int, password, name string) (*mongo.Client, error) {
var applyurl string
if password == "" {
applyurl = fmt.Sprintf("mongodb://%s:%d", ip, port)
} else {
applyurl = fmt.Sprintf("mongodb://%s:%s@%s:%d", name, password, ip, port)
}
credential := options.Credential{
AuthMechanism: "SCRAM-SHA-1",
}
clientOpts := options.Client().ApplyURI(applyurl).SetAuth(credential)
client, err := mongo.Connect(context.TODO(), clientOpts)
if err != nil {
msg = "无法连接到数据库:" + err.Error()
log.Error(msg)
return nil, errors.New(msg)
}
return client, nil
}