66 lines
1.4 KiB
Go
Executable File
66 lines
1.4 KiB
Go
Executable File
package repository
|
||
|
||
import (
|
||
"context"
|
||
"fmt"
|
||
|
||
"github.com/testcontainers/testcontainers-go"
|
||
"github.com/testcontainers/testcontainers-go/wait"
|
||
)
|
||
|
||
const (
|
||
MySQLUser = "root"
|
||
MySQLPassword = "password"
|
||
MySQLDatabase = "testdb"
|
||
MySQLPort = "3306"
|
||
)
|
||
|
||
// 啟動 MySQL container
|
||
func startMySQLContainer() (host string, port string, dsn string, tearDown func(), err error) {
|
||
ctx := context.Background()
|
||
|
||
req := testcontainers.ContainerRequest{
|
||
Image: "mysql:8.0",
|
||
Env: map[string]string{
|
||
"MYSQL_ROOT_PASSWORD": MySQLPassword,
|
||
"MYSQL_DATABASE": MySQLDatabase,
|
||
},
|
||
ExposedPorts: []string{"3306/tcp"},
|
||
WaitingFor: wait.ForListeningPort("3306/tcp"),
|
||
}
|
||
|
||
mysqlC, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{
|
||
ContainerRequest: req,
|
||
Started: true,
|
||
})
|
||
if err != nil {
|
||
return "", "", "", nil, err
|
||
}
|
||
|
||
mappedPort, err := mysqlC.MappedPort(ctx, "3306")
|
||
if err != nil {
|
||
return "", "", "", nil, err
|
||
}
|
||
|
||
containerHost, err := mysqlC.Host(ctx)
|
||
if err != nil {
|
||
return "", "", "", nil, err
|
||
}
|
||
|
||
// 組成 DSN(Data Source Name)
|
||
dsn = fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?parseTime=true",
|
||
MySQLUser,
|
||
MySQLPassword,
|
||
containerHost,
|
||
mappedPort.Port(),
|
||
MySQLDatabase,
|
||
)
|
||
|
||
tearDown = func() {
|
||
_ = mysqlC.Terminate(ctx)
|
||
}
|
||
|
||
fmt.Printf("MySQL ready at: %s\n", dsn)
|
||
return containerHost, mappedPort.Port(), dsn, tearDown, nil
|
||
}
|