Guest User

Untitled

a guest
Aug 28th, 2018
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.41 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "context"
  5. "fmt"
  6. "github.com/mongodb/mongo-go-driver/mongo"
  7. "log"
  8. "os"
  9. )
  10.  
  11. var (
  12. host, username, password, database string
  13. )
  14.  
  15. type key string
  16.  
  17. const (
  18. hostKey = key("hostKey")
  19. usernameKey = key("usernameKey")
  20. passwordKey = key("passwordKey")
  21. databaseKey = key("databaseKey")
  22. )
  23.  
  24. func init() {
  25. host = os.Getenv("TODO_MONGO_HOST")
  26. username = os.Getenv("TODO_MONGO_USERNAME")
  27. password = os.Getenv("TODO_MONGO_PASSWORD")
  28. database = os.Getenv("TODO_MONGO_DATABASE")
  29. }
  30.  
  31. func main() {
  32. ctx := context.Background()
  33. ctx = context.WithValue(ctx, hostKey, host)
  34. ctx = context.WithValue(ctx, usernameKey, username)
  35. ctx = context.WithValue(ctx, passwordKey, password)
  36. ctx = context.WithValue(ctx, databaseKey, database)
  37. _, err := configDB(ctx)
  38. if err != nil {
  39. log.Fatalf("todo: database configuration failed: %v", err)
  40. }
  41. }
  42.  
  43. func configDB(ctx context.Context) (*mongo.Database, error) {
  44. client, err := mongo.NewClient(fmt.Sprintf(
  45. `mongodb://%s:%s@%s/%s`,
  46. ctx.Value(usernameKey),
  47. ctx.Value(passwordKey),
  48. ctx.Value(hostKey),
  49. ctx.Value(databaseKey),
  50. ))
  51. if err != nil {
  52. return nil, fmt.Errorf("todo: couldn't connect to mongo: %v", err)
  53. }
  54. err = client.Connect(ctx)
  55. if err != nil {
  56. return nil, fmt.Errorf("todo: mongo client couldn't connect with background context: %v", err)
  57. }
  58. todoDB := client.Database("todo")
  59. fmt.Println("connection string:", client.ConnectionString())
  60. return todoDB, nil
  61. }
Add Comment
Please, Sign In to add comment