Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "context"
- "fmt"
- "github.com/mongodb/mongo-go-driver/mongo"
- "log"
- "os"
- )
- var (
- host, username, password, database string
- )
- type key string
- const (
- hostKey = key("hostKey")
- usernameKey = key("usernameKey")
- passwordKey = key("passwordKey")
- databaseKey = key("databaseKey")
- )
- func init() {
- host = os.Getenv("TODO_MONGO_HOST")
- username = os.Getenv("TODO_MONGO_USERNAME")
- password = os.Getenv("TODO_MONGO_PASSWORD")
- database = os.Getenv("TODO_MONGO_DATABASE")
- }
- func main() {
- ctx := context.Background()
- ctx = context.WithValue(ctx, hostKey, host)
- ctx = context.WithValue(ctx, usernameKey, username)
- ctx = context.WithValue(ctx, passwordKey, password)
- ctx = context.WithValue(ctx, databaseKey, database)
- _, err := configDB(ctx)
- if err != nil {
- log.Fatalf("todo: database configuration failed: %v", err)
- }
- }
- func configDB(ctx context.Context) (*mongo.Database, error) {
- client, err := mongo.NewClient(fmt.Sprintf(
- `mongodb://%s:%s@%s/%s`,
- ctx.Value(usernameKey),
- ctx.Value(passwordKey),
- ctx.Value(hostKey),
- ctx.Value(databaseKey),
- ))
- if err != nil {
- return nil, fmt.Errorf("todo: couldn't connect to mongo: %v", err)
- }
- err = client.Connect(ctx)
- if err != nil {
- return nil, fmt.Errorf("todo: mongo client couldn't connect with background context: %v", err)
- }
- todoDB := client.Database("todo")
- fmt.Println("connection string:", client.ConnectionString())
- return todoDB, nil
- }
Add Comment
Please, Sign In to add comment