forked from SpirentOrion/luddite
-
Notifications
You must be signed in to change notification settings - Fork 0
/
listener.go
94 lines (78 loc) · 2 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package luddite
import (
"crypto/tls"
"net"
"os"
"os/signal"
"syscall"
"time"
)
// Based on http://www.hydrogen18.com/blog/stop-listening-http-server-go.html,
// but stops on SIGINT instead of explicit Stop() call
type ListenerStoppedError struct {
}
func (e *ListenerStoppedError) Error() string {
return "Listener stopped"
}
type StoppableTCPListener struct {
*net.TCPListener
stop chan os.Signal
keepalives bool
}
func (sl *StoppableTCPListener) Accept() (net.Conn, error) {
for {
//Wait up to one second for a new connection
sl.TCPListener.SetDeadline(time.Now().Add(time.Second))
newConn, err := sl.TCPListener.AcceptTCP()
//Check for the channel being closed
select {
case <-sl.stop:
return nil, &ListenerStoppedError{}
default:
//If nothing came in on the channel, continue as normal
}
if err != nil {
netErr, ok := err.(net.Error)
//If this is a timeout, then continue to wait for
//new connections
if ok && netErr.Timeout() && netErr.Temporary() {
continue
}
return nil, err
}
if sl.keepalives {
newConn.SetKeepAlive(true)
newConn.SetKeepAlivePeriod(3 * time.Minute)
}
return newConn, err
}
}
func NewStoppableTCPListener(addr string, keepalives bool) (net.Listener, error) {
l, err := net.Listen("tcp", addr)
if err != nil {
return nil, err
}
sl := &StoppableTCPListener{
l.(*net.TCPListener),
make(chan os.Signal, 1),
keepalives,
}
signal.Notify(sl.stop, syscall.SIGINT)
return sl, nil
}
func NewStoppableTLSListener(addr string, keepalives bool, certFile string, keyFile string) (net.Listener, error) {
var err error
tlsConfig := &tls.Config{}
tlsConfig.NextProtos = []string{"http/1.1"}
tlsConfig.Certificates = make([]tls.Certificate, 1)
tlsConfig.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return nil, err
}
stl, err := NewStoppableTCPListener(addr, keepalives)
if err != nil {
return nil, err
}
tlsListener := tls.NewListener(stl, tlsConfig)
return tlsListener, nil
}