github.com/angryronald/go-kit@v0.0.0-20240505173814-ff2bd9c79dbf/test/docker/mongo/mongo.go (about)

     1  package mongo
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"log"
     7  	"time"
     8  
     9  	"go.mongodb.org/mongo-driver/mongo"
    10  	mongoOptions "go.mongodb.org/mongo-driver/mongo/options"
    11  
    12  	"github.com/ory/dockertest/v3"
    13  	"github.com/sirupsen/logrus"
    14  )
    15  
    16  func GenerateInstance(pool *dockertest.Pool) (*mongo.Client, *dockertest.Resource) {
    17  	// Set up options for MongoDB container
    18  	options := &dockertest.RunOptions{
    19  		Repository: "mongo",
    20  		Tag:        "4.4",
    21  		Env: []string{
    22  			"MONGO_INITDB_ROOT_USERNAME=root",
    23  			"MONGO_INITDB_ROOT_PASSWORD=example",
    24  		},
    25  	}
    26  
    27  	// Run MongoDB container
    28  	resource, err := pool.RunWithOptions(options)
    29  	if err != nil {
    30  		log.Fatalf("Could not start MongoDB container: %s", err)
    31  	}
    32  
    33  	// Wait for MongoDB to be ready
    34  	if err := pool.Retry(func() error {
    35  		clientOptions := mongoOptions.Client().ApplyURI(fmt.Sprintf(
    36  			"mongodb://root:example@%s:%s",
    37  			resource.GetBoundIP("27017/tcp"),
    38  			resource.GetPort("27017/tcp"),
    39  		))
    40  		ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    41  		defer cancel()
    42  		client, err := mongo.Connect(ctx, clientOptions)
    43  		if err != nil {
    44  			return err
    45  		}
    46  		err = client.Ping(ctx, nil)
    47  		return err
    48  	}); err != nil {
    49  		log.Fatalf("Could not connect to MongoDB: %s", err)
    50  	}
    51  
    52  	// At this point, MongoDB should be running and ready to use.
    53  
    54  	// You can use the MongoDB Go driver to interact with MongoDB.
    55  	// For example, you can create a new MongoDB client and perform operations:
    56  
    57  	// Connect to MongoDB
    58  	clientOptions := mongoOptions.Client().ApplyURI(fmt.Sprintf(
    59  		"mongodb://root:example@%s:%s",
    60  		resource.GetBoundIP("27017/tcp"),
    61  		resource.GetPort("27017/tcp"),
    62  	))
    63  
    64  	client, err := mongo.Connect(context.Background(), clientOptions)
    65  	if err != nil {
    66  		log.Fatalf("Could not connect to MongoDB: %s", err)
    67  	}
    68  
    69  	logrus.Debugf("Connected to MongoDB")
    70  
    71  	return client, resource
    72  }