github.com/ghodss/etcd@v0.3.1-0.20140417172404-cc329bfa55cb/server/listener.go (about)

     1  package server
     2  
     3  import (
     4  	"crypto/tls"
     5  	"net"
     6  
     7  	"github.com/coreos/etcd/log"
     8  )
     9  
    10  // TLSServerConfig generates tls configuration based on TLSInfo
    11  // If any error happens, this function will call log.Fatal
    12  func TLSServerConfig(info *TLSInfo) *tls.Config {
    13  	if info.KeyFile == "" || info.CertFile == "" {
    14  		return nil
    15  	}
    16  
    17  	cfg, err := info.ServerConfig()
    18  	if err != nil {
    19  		log.Fatal("TLS info error: ", err)
    20  	}
    21  	return cfg
    22  }
    23  
    24  // NewListener creates a net.Listener
    25  // If the given scheme is "https", it will use TLS config to set listener.
    26  // If any error happens, this function will call log.Fatal
    27  func NewListener(scheme, addr string, cfg *tls.Config) net.Listener {
    28  	if scheme == "https" {
    29  		l, err := newTLSListener(addr, cfg)
    30  		if err != nil {
    31  			log.Fatal("Failed to create TLS listener: ", err)
    32  		}
    33  		return l
    34  	}
    35  
    36  	l, err := newListener(addr)
    37  	if err != nil {
    38  		log.Fatal("Failed to create listener: ", err)
    39  	}
    40  	return l
    41  }
    42  
    43  func newListener(addr string) (net.Listener, error) {
    44  	if addr == "" {
    45  		addr = ":http"
    46  	}
    47  	l, e := net.Listen("tcp", addr)
    48  	if e != nil {
    49  		return nil, e
    50  	}
    51  	return l, nil
    52  }
    53  
    54  func newTLSListener(addr string, cfg *tls.Config) (net.Listener, error) {
    55  	if addr == "" {
    56  		addr = ":https"
    57  	}
    58  
    59  	conn, err := net.Listen("tcp", addr)
    60  	if err != nil {
    61  		return nil, err
    62  	}
    63  
    64  	return tls.NewListener(conn, cfg), nil
    65  }