Persistent No Reachable Server to Replica Set in MongoDB Atlas with Go mgo
When connecting to a MongoDB Atlas replica set using the Golang mgo library, a "no reachable server" error can sometimes occur. This issue can be resolved by leveraging a customized DialServer function in the mgo DialInfo struct.
The following code snippet demonstrates how to establish a successful connection to a replica set using custom TLS configurations:
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:
Alternatively, the mgo.ParseURL() method can be used to parse the MongoDB Atlas URI string. However, SSL is currently not supported by this method. A workaround is to remove the ssl=true line from the URI string before parsing.
The above is the detailed content of How to Resolve \'No Reachable Server\' Errors When Connecting to MongoDB Atlas Replica Sets with Go\'s mgo Library?. For more information, please follow other related articles on the PHP Chinese website!