Last active
December 29, 2020 17:53
-
-
Save nkreiger/7d7772de70d01770f4101bc897a66999 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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