Home > Backend Development > Golang > Why Does My Go mgo Driver Fail to Connect to MongoDB Atlas Replica Set with a \'No Reachable Server\' Error?

Why Does My Go mgo Driver Fail to Connect to MongoDB Atlas Replica Set with a \'No Reachable Server\' Error?

Susan Sarandon
Release: 2024-11-30 09:57:10
Original
663 people have browsed it

Why Does My Go mgo Driver Fail to Connect to MongoDB Atlas Replica Set with a

Connecting to MongoDB Atlas Using Golang Mgo: Resolving "No Reachable Server to Replica Set" Issue

Question:

When connecting to a replica set on MongoDB Atlas using the Golang mgo driver, an error message of "no reachable server" is encountered despite successful connections with other languages and the regular Mongo client.

Answer:

A modified version of the mgo code snippet below successfully establishes a connection to MongoDB Atlas using the provided example parameters:

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

Consideration:

  • You can specify only one of the replica set members as a seed, such as: Addrs: []string{"prefix2.mongodb.net:27017"}.
  • The mgo.ParseURL() method does not currently support SSL, so using it to parse the MongoDB Atlas URI string requires removing the ssl=true line beforehand.

The above is the detailed content of Why Does My Go mgo Driver Fail to Connect to MongoDB Atlas Replica Set with a \'No Reachable Server\' Error?. 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