In general, our database are configured for network access, but because of the different service deployment architecture, sometimes need access through the public network MongoDB database, this time in order to prevent port scans and off the library, you need to configure MongoDB access to TLS, that the Go how should achieve it?
rely
MongoDB instance arranged TLS public network access
Go to MongoDB drive globalsign / mgo
Go implementation code:
package model
import (
"crypto/tls"
"crypto/x509"
"errors"
"github.com/globalsign/mgo"
"io/ioutil"
"log"
"net"
)
func main() {
dsn := "mongodb://user:password@host/database"
dialInfo, err := mgo.ParseURL(dsn)
if err != nil {
log.Panic(err)
}
// read pemfile data
pemData, err := ioutil.ReadFile("./pemfile")
if err != nil {
log.Panic(err)
}
roots := x509.NewCertPool()
if !roots.AppendCertsFromPEM(pemData) {
log.Panic(errors.New("failed to parse root certificate"))
}
// set tls config
tlsConfig := &tls.Config{
RootCAs: roots,
InsecureSkipVerify: true,
}
// update dialserver with tls Dial
dialInfo.DialServer = func(addr *mgo.ServerAddr) (net.Conn, error) {
conn, err := tls.Dial("tcp", addr.String(), tlsConfig)
if err != nil {
log.Println(err)
}
return conn, err
}
session, err := mgo.DialWithInfo(dialInfo)
if err != nil {
log.Panic(err.Error())
}
// db operation with session
}
By the above code, we can MongoDB instance tls connected by the public network, when connected, the operation and the database of connections within the network.
http://www.songjiayang.com/posts/mongo-connect-with-tls-in-go