如何使用MongoDB 3.6中的新URL从Golang连接

I tried to connect to mongodb Atlas using golang drivers.

tlsConfig := &tls.Config{}

var mongoURI = "mongodb+srv://admin:password@prefix.mongodb.net:27017/dbname"
dialInfo, err := mgo.ParseURL(mongoURI)
if err != nil {
    panic(err)
}
dialInfo.DialServer = func(addr *mgo.ServerAddr) (net.Conn, error) {
    conn, err := tls.Dial("tcp", addr.String(), tlsConfig)
    return conn, err
}

session, err := mgo.DialWithInfo(dialInfo)
if err != nil {
    println("error")
    log.Fatal(err)
}
_ = session
c := session.DB("Token").C("_Users")
user := &User{firstName: "username"}
err = c.Insert(user)
if err != nil {
    println("error Again")
}

I am not getting an error not getting connected. I am wondering what could be the reason.' Any help is appreciated.

I tried to create DialInfo using below code

    dialInfo := &mgo.DialInfo{
    Addrs:     []string{"prefix.mongodb.net:27017"},
    Database:  "dbname",
    Mechanism: "SCRAM",
    Timeout:   10 * time.Second,
    Username:  "admin",
    Password:  "passwrd",
}

Now I am getting no reachable servers

I could only see that the code started, then nothing

As you have figured out, this is because DialInfo by default has a zero timeout. The call will block forever waiting for a connection to be established. You can also specify a timeout with:

dialInfo.Timeout = time.Duration(30)
session, err := mgo.DialWithInfo(dialInfo)

Now I am getting no reachable servers

This is because globalsign/mgo does not currently support SRV connection string URI yet. See issues 112. You can use the non-srv connection URI format (MongoDB v3.4), see a related question StackOverflow: 41173720.

You can use mongo-go-driver instead if you would like to connect using the SRV connection URI, for example:

mongoURI := "mongodb+srv://admin:password@prefix.mongodb.net/dbname?ssl=true&retryWrites=true"

client, err := mongo.NewClient(options.Client().ApplyURI(mongoURI))
if err != nil {
    log.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
err = client.Connect(ctx)
defer client.Disconnect(ctx)

if err != nil {
    log.Fatal(err)
}
database := client.Database("go")
collection := database.Collection("atlas")

The above example is compatible with the current version v1.0.0