-
Notifications
You must be signed in to change notification settings - Fork 36
Connect Mongo Client
Ken Chen edited this page May 19, 2019
·
5 revisions
Examples to connect to a mongo cluster using mongo-go-driver.
$ mongo "mongodb://user:password@localhost/?replicaSet=replset&authSource=admin"
uri := "mongodb://user:password@localhost/?replicaSet=replset&authSource=admin"
client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(uri))
if err != nil {
fmt.Println(err.Error())
}
opts := options.Client()
opts.SetHosts([]string{"localhost:27017"})
auth := options.Credential{Username: "user", Password: "password", AuthSource: "admin"}
opts.SetAuth(auth)
opts.SetReplicaSet("replset")
client, err := mongo.Connect(context.TODO(), opts)
if err != nil {
fmt.Println(err.Error())
}
$ mongo "mongodb://user:password@localhost/?replicaSet=replset&authSource=admin" \
--sslCAFile ca.crt --sslPEMKeyFile client.pem
uri := "mongodb://user:password@localhost/?replicaSet=replset&authSource=admin"
opts := options.Client().ApplyURI(uri)
caBytes, _ := ioutil.ReadFile("ca.crt")
clientBytes, _ := ioutil.ReadFile("client.pem")
roots := x509.NewCertPool()
if ok := roots.AppendCertsFromPEM(caBytes); !ok {
return errors.New("failed to parse root certificate")
}
certs, err := tls.X509KeyPair(clientBytes, clientBytes)
if err != nil {
return err
}
cfg := &tls.Config{RootCAs: roots, Certificates: []tls.Certificate{certs}}
opts.SetTLSConfig(cfg)
client, err := mongo.Connect(context.TODO(), opts)
if err != nil {
fmt.Println(err.Error())
}