/
redisdocker.go
73 lines (58 loc) 路 1.38 KB
/
redisdocker.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package redisdocker
import (
"fmt"
"io"
"github.com/gomodule/redigo/redis"
"github.com/ory/dockertest/v3"
)
// ensure Container implements the io.Closer interface.
var _ io.Closer = (*Container)(nil)
// Container represents a Docker container
// running a PostgreSQL image.
type Container struct {
res *dockertest.Resource
port string
}
// Port returns the container host port mapped
// to the database running inside it.
func (c Container) Port() string {
return c.port
}
// Close removes the Docker container.
func (c Container) Close() error {
return c.res.Close()
}
// NewContainer starts a new redis client in a docker container.
func NewContainer() (
*Container,
error,
) {
var err error
pool, err := dockertest.NewPool("")
if err != nil {
return nil, fmt.Errorf("could not connect to docker %w", err)
}
resource, err := pool.Run("redis", "3.2", nil)
if err != nil {
return nil, fmt.Errorf("could not start resource: %w", err)
}
err = pool.Retry(func() error {
addr := fmt.Sprintf("localhost:%s", resource.GetPort("6379/tcp"))
conn, err := redis.Dial("tcp", addr)
if err != nil {
return err
}
_, err = redis.String(conn.Do("PING"))
if err != nil {
return err
}
return nil
})
if err != nil {
return nil, fmt.Errorf("could not connect to docker: %w", err)
}
return &Container{
res: resource,
port: resource.GetPort("6379/tcp"),
}, nil
}