-
Notifications
You must be signed in to change notification settings - Fork 0
/
tracking_listener.go
91 lines (77 loc) · 1.72 KB
/
tracking_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
package httputil2
import (
"net"
"sync"
)
type trackingListener struct {
net.Listener
wg sync.WaitGroup
closed func()
}
// A net.Listener that tracks the livelyhood of the connections such that
// the wg internal counter will go back to it's initial value once the
// listener and all it's issued net.Conn are closed.
//
// This is useful for gracefully shutting down a server where first new
// connections are stoppped being accepted and then all the client connections
// are being shutdown as requests terminate.
//
// Note that net/http.Server only provides HTTP/2 when ListenAndServeTLS is
// called directly (whereas here you would use the Serve(l) function).
func NewTrackingListener(l net.Listener, wg sync.WaitGroup) net.Listener {
var once sync.Once
wg.Add(1)
return &trackingListener{
Listener: l,
wg: wg,
closed: func() {
once.Do(wg.Done)
},
}
}
func (l *trackingListener) Accept() (net.Conn, error) {
conn, err := l.Listener.Accept()
if err != nil {
l.closed()
return nil, err
}
return newTrackedConn(conn, l.wg), err
}
func (l *trackingListener) Close() error {
err := l.Listener.Close()
l.closed()
return err
}
type trackedConn struct {
net.Conn
closed func()
}
func newTrackedConn(c net.Conn, wg sync.WaitGroup) net.Conn {
var once sync.Once
wg.Add(1)
return &trackedConn{
Conn: c,
closed: func() {
once.Do(wg.Done)
},
}
}
func (c *trackedConn) Read(b []byte) (n int, err error) {
n, err = c.Conn.Read(b)
if err != nil {
c.closed()
}
return n, err
}
func (c *trackedConn) Write(b []byte) (n int, err error) {
n, err = c.Conn.Write(b)
if err != nil {
c.closed()
}
return n, err
}
func (c *trackedConn) Close() error {
err := c.Conn.Close()
c.closed()
return err
}