Resolving "No Reachable Server" Connection Issues with MongoDB Atlas and Golang's Mgo
When connecting to a MongoDB Atlas replica set using Golang's mgo, you may encounter the frustrating error of "no reachable server." Despite trying various URL and dial configurations, the issue persists.
To resolve this, consider the following solution using Mgo's DialWithInfo function:
import ( "gopkg.in/mgo.v2" "crypto/tls" "net" ) tlsConfig := &tls.Config{} dialInfo := &mgo.DialInfo{ Addrs: []string{"prefix1.mongodb.net:27017", "prefix2.mongodb.net:27017", "prefix3.mongodb.net:27017"}, Database: "authDatabaseName", Username: "user", Password: "pass", } 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)
In this code, the DialInfo.DialServer function configures SSL connectivity to the replica set members. You can also specify only one member as a seed, such as "prefix2.mongodb.net:27017" for Addrs.
Alternatively, using ParseURL to parse the MongoDB Atlas URI string is another option. However, currently, SSL is not supported using this method (mgo.V2 PR:304).
To work around this, remove the ssl=true line before parsing:
//URI without ssl=true var mongoURI = "mongodb://username:[email protected],prefix2.mongodb.net,prefix3.mongodb.net/dbName?replicaSet=replName&authSource=admin" dialInfo, err := mgo.ParseURL(mongoURI) //Below part is similar to above. tlsConfig := &tls.Config{} dialInfo.DialServer = func(addr *mgo.ServerAddr) (net.Conn, error) { conn, err := tls.Dial("tcp", addr.String(), tlsConfig) return conn, err } session, _ := mgo.DialWithInfo(dialInfo)
The above is the detailed content of How to Resolve \'No Reachable Server\' Errors When Connecting to MongoDB Atlas with Golang\'s mgo?. For more information, please follow other related articles on the PHP Chinese website!