tcp_socket.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. // Package sockets provides helper functions to create and configure Unix or TCP
  2. // sockets.
  3. package sockets
  4. import (
  5. "crypto/tls"
  6. "net"
  7. "net/http"
  8. "time"
  9. )
  10. // NewTCPSocket creates a TCP socket listener with the specified address and
  11. // and the specified tls configuration. If TLSConfig is set, will encapsulate the
  12. // TCP listener inside a TLS one.
  13. func NewTCPSocket(addr string, tlsConfig *tls.Config) (net.Listener, error) {
  14. l, err := net.Listen("tcp", addr)
  15. if err != nil {
  16. return nil, err
  17. }
  18. if tlsConfig != nil {
  19. tlsConfig.NextProtos = []string{"http/1.1"}
  20. l = tls.NewListener(l, tlsConfig)
  21. }
  22. return l, nil
  23. }
  24. // ConfigureTCPTransport configures the specified Transport according to the
  25. // specified proto and addr.
  26. // If the proto is unix (using a unix socket to communicate) the compression
  27. // is disabled.
  28. func ConfigureTCPTransport(tr *http.Transport, proto, addr string) {
  29. // Why 32? See https://github.com/docker/docker/pull/8035.
  30. timeout := 32 * time.Second
  31. if proto == "unix" {
  32. // No need for compression in local communications.
  33. tr.DisableCompression = true
  34. tr.Dial = func(_, _ string) (net.Conn, error) {
  35. return net.DialTimeout(proto, addr, timeout)
  36. }
  37. } else {
  38. tr.Proxy = http.ProxyFromEnvironment
  39. tr.Dial = (&net.Dialer{Timeout: timeout}).Dial
  40. }
  41. }