Skip to content

Instantly share code, notes, and snippets.

@Dineshs91
Last active April 21, 2019 10:45
Show Gist options
  • Save Dineshs91/101b34c9f2f6558a2f670cf75bf862df to your computer and use it in GitHub Desktop.
Save Dineshs91/101b34c9f2f6558a2f670cf75bf862df to your computer and use it in GitHub Desktop.
database connection for go-mongo-driver medium article
package db
import (
"context"
"fmt"
"log"
"os"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
var mongoClient *mongo.Client
// Datastore is a wrapper around mongo.Client.
type Datastore struct {
Client *mongo.Client
DatabaseName string
}
// New creates a new mongo.Client
func New() *Datastore {
databaseName, ok := os.LookupEnv("MONGO_DATABASE_NAME")
if !ok {
databaseName = "uptime"
}
mongoHost := os.Getenv("MONGO_HOST")
mongoPass := os.Getenv("MONGO_INITDB_ROOT_PASSWORD")
connString := fmt.Sprintf("mongodb://root:%s@%s:27017", mongoPass, mongoHost)
if mongoClient == nil {
client, err := mongo.NewClient(options.Client().ApplyURI(connString))
if err != nil {
log.Fatal(err)
}
err = client.Connect(context.TODO())
if err != nil {
log.Fatal(err)
}
mongoClient = client
}
return &Datastore{
Client: mongoClient,
DatabaseName: databaseName,
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment