docker_test.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package main
  2. import (
  3. "context"
  4. "os"
  5. "github.com/docker/docker/api/types"
  6. "github.com/docker/docker/api/types/container"
  7. "github.com/docker/docker/client"
  8. )
  9. func startContainer(cfg *container.Config, hostCfg *container.HostConfig, name string) (string, error) {
  10. c, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
  11. if err != nil {
  12. return "", err
  13. }
  14. defer c.Close()
  15. if !isDarwin {
  16. hostCfg.NetworkMode = "host"
  17. }
  18. container, err := c.ContainerCreate(context.Background(), cfg, hostCfg, nil, nil, name)
  19. if err != nil {
  20. return "", err
  21. }
  22. if err = c.ContainerStart(context.Background(), container.ID, types.ContainerStartOptions{}); err != nil {
  23. return "", err
  24. }
  25. response, err := c.ContainerAttach(context.Background(), container.ID, types.ContainerAttachOptions{
  26. Stdout: true,
  27. Stderr: true,
  28. Logs: true,
  29. })
  30. if err != nil {
  31. return "", err
  32. }
  33. go func() {
  34. response.Reader.WriteTo(os.Stderr)
  35. }()
  36. return container.ID, nil
  37. }
  38. func cleanContainer(id string) error {
  39. c, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
  40. if err != nil {
  41. return err
  42. }
  43. defer c.Close()
  44. removeOpts := types.ContainerRemoveOptions{Force: true}
  45. return c.ContainerRemove(context.Background(), id, removeOpts)
  46. }