Skip to content

Instantly share code, notes, and snippets.

@ncomet
Created May 2, 2022 14:55
Show Gist options
  • Save ncomet/efb1b9cc5af8b27d3568c3aa5633571c to your computer and use it in GitHub Desktop.
Save ncomet/efb1b9cc5af8b27d3568c3aa5633571c to your computer and use it in GitHub Desktop.
Container preparation
func prepareContainer(ctx context.Context, image image) (testcontainers.Container, string, error) {
req := testcontainers.ContainerRequest{
Image: image.name,
ExposedPorts: []string{image.port + "/tcp"},
WaitingFor: wait.ForListeningPort(nat.Port(image.port)),
}
container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{
ContainerRequest: req,
Started: true,
})
if err != nil {
return nil, "", err
}
hostIP, err := container.Host(ctx)
if err != nil {
return nil, "", err
}
mappedPort, err := container.MappedPort(ctx, nat.Port(image.port))
if err != nil {
return nil, "", err
}
var uri string
switch image {
case mongoDB:
uri = fmt.Sprintf("mongodb://%s:%s", hostIP, mappedPort.Port())
default:
return nil, "", errors.New("TestContainers: unsupported image: " + image.name)
}
log.Printf("TestContainers: container %s is now running at %s\n", req.Image, uri)
return container, uri, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment