Skip to content

Instantly share code, notes, and snippets.

@nkreiger
Last active December 29, 2020 17:53
Show Gist options
  • Save nkreiger/7d7772de70d01770f4101bc897a66999 to your computer and use it in GitHub Desktop.
Save nkreiger/7d7772de70d01770f4101bc897a66999 to your computer and use it in GitHub Desktop.
// Connect returns a successfully connected mongo client
func Connect(ctx context.Context) (*mongo.Client, error) {
url := "mongodb://admin:admin@localhost:27017"
log.Printf("connect to mongodb at: %v", url)
opts := options.Client()
opts.ApplyURI(url)
client, err := mongo.Connect(ctx, opts)
if err != nil {
msg := fmt.Sprintf("invalid mongodb connection: %v", err)
log.Println(msg)
return nil, fmt.Errorf(msg)
}
// test connection
err = client.Ping(ctx, readpref.Primary())
if err != nil {
log.Printf("connection test to mongodb client failed: %v", err)
return nil, fmt.Errorf(fmt.Sprintf("connection test to mongodb client failed: %v", err))
}
log.Println("connected successfully to mongodb")
return client, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment