client.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package request
  2. import (
  3. "net"
  4. "net/http"
  5. "testing"
  6. "time"
  7. "github.com/docker/docker/api"
  8. "github.com/docker/docker/client"
  9. "github.com/docker/go-connections/sockets"
  10. "github.com/docker/go-connections/tlsconfig"
  11. "github.com/stretchr/testify/require"
  12. )
  13. // NewAPIClient returns a docker API client configured from environment variables
  14. func NewAPIClient(t *testing.T) client.APIClient {
  15. clt, err := client.NewEnvClient()
  16. require.NoError(t, err)
  17. return clt
  18. }
  19. // NewTLSAPIClient returns a docker API client configured with the
  20. // provided TLS settings
  21. func NewTLSAPIClient(t *testing.T, host, cacertPath, certPath, keyPath string) (client.APIClient, error) {
  22. opts := tlsconfig.Options{
  23. CAFile: cacertPath,
  24. CertFile: certPath,
  25. KeyFile: keyPath,
  26. ExclusiveRootPools: true,
  27. }
  28. config, err := tlsconfig.Client(opts)
  29. require.Nil(t, err)
  30. tr := &http.Transport{
  31. TLSClientConfig: config,
  32. DialContext: (&net.Dialer{
  33. KeepAlive: 30 * time.Second,
  34. Timeout: 30 * time.Second,
  35. }).DialContext,
  36. }
  37. proto, addr, _, err := client.ParseHost(host)
  38. require.Nil(t, err)
  39. sockets.ConfigureTransport(tr, proto, addr)
  40. httpClient := &http.Client{
  41. Transport: tr,
  42. CheckRedirect: client.CheckRedirect,
  43. }
  44. verStr := api.DefaultVersion
  45. customHeaders := map[string]string{}
  46. return client.NewClient(host, verStr, httpClient, customHeaders)
  47. }