-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathconnection_tracker.go
64 lines (55 loc) · 1.34 KB
/
connection_tracker.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
package main
import "net"
import "net/http"
import "time"
type ConnectionTracker struct {
opened chan net.Conn
closed chan net.Conn
shutdown chan *time.Timer
finished chan struct{}
ConnState func(net.Conn, http.ConnState)
}
func NewConnectionTracker() (tracker *ConnectionTracker) {
tracker = &ConnectionTracker{
opened: make(chan net.Conn),
closed: make(chan net.Conn),
shutdown: make(chan *time.Timer),
finished: make(chan struct{}),
}
tracker.ConnState = func(nc net.Conn, state http.ConnState) {
switch state {
case http.StateNew:
tracker.opened <- nc
case http.StateClosed, http.StateHijacked:
tracker.closed <- nc
}
}
go tracker.track()
return
}
func (tracker *ConnectionTracker) Shutdown(timeout time.Duration) {
tracker.shutdown <- time.NewTimer(timeout)
<-tracker.finished
}
func (tracker *ConnectionTracker) track() {
connections := map[net.Conn]struct{}{}
var deadline <-chan time.Time
for deadline == nil || len(connections) > 0 {
select {
case nc := <-tracker.opened:
connections[nc] = struct{}{}
case nc := <-tracker.closed:
delete(connections, nc)
case timeout := <-tracker.shutdown:
deadline = timeout.C
for nc := range connections {
nc.(*net.TCPConn).CloseRead()
}
case <-deadline:
for nc := range connections {
nc.Close()
}
}
}
close(tracker.finished)
}