Home > Backend Development > Golang > How to Resolve \'No Reachable Server\' Errors When Connecting to MongoDB Atlas with Golang\'s mgo?

How to Resolve \'No Reachable Server\' Errors When Connecting to MongoDB Atlas with Golang\'s mgo?

Patricia Arquette
Release: 2024-11-27 20:01:11
Original
587 people have browsed it

How to Resolve

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)
Copy after login

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)
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template