2017-04-21 164 views
0

我正在嘗試使用mgo連接到MongoDB Atlas免費羣集。CreateSession:無法訪問服務器 - mgo

Golang代碼 -

package main 

import (
    "fmt" 
    "gopkg.in/mgo.v2" 
    "time" 
    "log" 
) 

const (
    AuthDatabase = "mydatabase" 
    AuthUserName = "databaseadmin" 
    AuthPassword = "databasepassword" 
    ReplicaSetName = "myproject-shard-0" 
) 

func main(){ 

MongoDBHosts := []string{ 
    "myproject-shard-00-00-w4vds.mongodb.net:27017", 
    "myproject-shard-00-01-w4vds.mongodb.net:27017", 
    "myproject-shard-00-02-w4vds.mongodb.net:27017", 
} 

mongoDBDialInfo := &mgo.DialInfo{ 
    Addrs: MongoDBHosts, 
    Timeout: 60 * time.Second, 
    Database: AuthDatabase, 
    Username: AuthUserName, 
    Password: AuthPassword, 
    ReplicaSetName: ReplicaSetName, 
} 

mongoSession, err := mgo.DialWithInfo(mongoDBDialInfo) 
if err != nil { 
    log.Fatalf("CreateSession: %s\n", err) 
} 

defer mongoSession.Close() 
fmt.Printf("Connected to replica set %v!\n", mongoSession.LiveServers()) 
} 

錯誤消息 -

了createSession:無可達服務器

環境

我使用MongoDB的空閒簇與谷歌的App Engine SDK GO

回答

0

要連接到MongoDB的地圖集,你需要SSL

先決條件

TLS/SSL 

    Clients must have support for TLS/SSL to connect to an Atlas cluster. 

    Clients must have support for the SNI TLS extension to connect to an Atlas M0 Free Tier cluster. 


Whitelist 

    To access a cluster, you must connect from an IP address on the Atlas group’s IP whitelist. If you need to add an IP address to the whitelist, you can do so in the Connect dialog. You can also add the IP address from the Security tab. 

因此,我不得不改變以下的一段代碼

mongoDBDialInfo := &mgo.DialInfo{ 
    Addrs: MongoDBHosts, 
    Timeout: 60 * time.Second, 
    Database: AuthDatabase, 
    Username: AuthUserName, 
    Password: AuthPassword, 
    ReplicaSetName: ReplicaSetName, 
} 

mongoDBDialInfo.DialServer = func(addr *mgo.ServerAddr) (net.Conn, error) { 
     conn, err := tls.Dial("tcp", addr.String(), tlsConfig) 
     return conn, err 
    } 

我不得不進口下列太

"crypto/tls" 
"net"