Skip to content

Instantly share code, notes, and snippets.

@wemgl
Last active August 31, 2018 18:05
Show Gist options
  • Save wemgl/a0846ba08b08578e721f897a79d551b2 to your computer and use it in GitHub Desktop.
Save wemgl/a0846ba08b08578e721f897a79d551b2 to your computer and use it in GitHub Desktop.
Connecting to a MongoDB Database from Go
// package declaration and imports omitted for brevity
type key string
const (
hostKey = key("hostKey")
usernameKey = key("usernameKey")
passwordKey = key("passwordKey")
databaseKey = key("databaseKey")
)
func main() {
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
ctx = context.WithValue(ctx, hostKey, os.Getenv("TODO_MONGO_HOST"))
ctx = context.WithValue(ctx, usernameKey, os.Getenv("TODO_MONGO_USERNAME"))
ctx = context.WithValue(ctx, passwordKey, os.Getenv("TODO_MONGO_PASSWORD"))
ctx = context.WithValue(ctx, databaseKey, os.Getenv("TODO_MONGO_DATABASE"))
db, err := configDB(ctx)
if err != nil {
log.Fatalf("todo: database configuration failed: %v", err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment