github.com/walkingsparrow/docker@v1.4.2-0.20151218153551-b708a2249bfa/pkg/sockets/tcp_socket.go (about)

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