Home >Backend Development >Golang >Why Does My Golang mgo Connection to MongoDB Atlas Keep Failing with a \'No Reachable Server\' Error?
Connecting to MongoDB Atlas using Golang mgo: Persistent "no reachable server" to replica set
This error message commonly arises when attempting to connect to a MongoDB Atlas replica set using Golang's mgo driver. To resolve this issue, consider the following steps:
Utilizing the mgo code snippet provided below:
import ( "gopkg.in/mgo.v2" "crypto/tls" "net" ) // Configure TLS settings tlsConfig := &tls.Config{} // Initialize the DialInfo object dialInfo := &mgo.DialInfo{ Addrs: []string{"prefix1.mongodb.net:27017", "prefix2.mongodb.net:27017", "prefix3.mongodb.net:27017"}, Database: "authDatabaseName", Username: "user", Password: "pass", } // Override the default DialServer method dialInfo.DialServer = func(addr *mgo.ServerAddr) (net.Conn, error) { conn, err := tls.Dial("tcp", addr.String(), tlsConfig) return conn, err } // Establish the connection using DialWithInfo session, err := mgo.DialWithInfo(dialInfo)
Keep in mind that specifying a single replica set member as a seed is an equally valid option:
Addrs: []string{"prefix2.mongodb.net:27017"}
For further insights, refer to the following resources:
Update:
Alternatively, the mgo.ParseURL() method can be employed to interpret the MongoDB Atlas URI string. However, it currently lacks support for SSL.
As a workaround, you can remove the ssl=true parameter 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) // Subsequent code remains similar to the previous example.
The above is the detailed content of Why Does My Golang mgo Connection to MongoDB Atlas Keep Failing with a \'No Reachable Server\' Error?. For more information, please follow other related articles on the PHP Chinese website!