Last active
April 21, 2019 10:45
-
-
Save Dineshs91/101b34c9f2f6558a2f670cf75bf862df to your computer and use it in GitHub Desktop.
database connection for go-mongo-driver medium article
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
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