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