title: How to Manage MongoDB Client across Packages in Golang
body: <p>I am currently starting out with <code>MongoDB</code> on <code>GoLang</code>. My current use case is this.</p>
  
  <p>I wish to initialize connection to my <code>MongoDB Database</code> in a particular package and use the returned <code>client</code> across several other local packages. Here is what I have tried,</p>
  
  <p>I have initialized the connection to <code>MongoDB</code> inside a package called <code>dataLayer</code> as below</p>
  
  <pre><code>package dataLayer
  
  import (
      "context"
      "log"
      "time"
  
      "go.mongodb.org/mongo-driver/mongo"
      "go.mongodb.org/mongo-driver/mongo/options"
      "go.mongodb.org/mongo-driver/mongo/readpref"
  )
  
  func InitDataLayer() {
      ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
      defer cancel()
      client, err := mongo.Connect(ctx, options.Client().ApplyURI(credentials.MONGO_DB_ATLAS_URI))
      if err != nil {
          log.Fatal(err)
      } else {
          log.Println("Connected to Database")
      }
  }
  </code></pre>
  
  <p>Now if I wish to use the returned <code>client</code> in other packages, is it production safe to keep on calling <code>initDataLayer</code> over and over again to get back a <code>client</code>?</p>
  
  <p>Thanks alot.</p>