This repository has been archived by the owner on Nov 20, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
http_server.go
105 lines (85 loc) · 2.04 KB
/
http_server.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
95
96
97
98
99
100
101
102
103
104
105
package http_server
import (
"net"
"net/http"
"os"
"sync"
"github.com/tedsuo/ifrit"
)
type httpServer struct {
address string
handler http.Handler
connectionWaitGroup *sync.WaitGroup
inactiveConnections map[net.Conn]struct{}
inactiveConnectionsMu *sync.Mutex
stoppingChan chan struct{}
}
func New(address string, handler http.Handler) ifrit.Runner {
return &httpServer{
address: address,
handler: handler,
}
}
func (s *httpServer) Run(signals <-chan os.Signal, ready chan<- struct{}) error {
s.connectionWaitGroup = new(sync.WaitGroup)
s.inactiveConnectionsMu = new(sync.Mutex)
s.inactiveConnections = make(map[net.Conn]struct{})
s.stoppingChan = make(chan struct{})
server := http.Server{
Handler: s.handler,
ConnState: func(conn net.Conn, state http.ConnState) {
switch state {
case http.StateNew:
s.connectionWaitGroup.Add(1)
s.addInactiveConnection(conn)
case http.StateIdle:
s.addInactiveConnection(conn)
case http.StateActive:
s.removeInactiveConnection(conn)
case http.StateHijacked, http.StateClosed:
s.removeInactiveConnection(conn)
s.connectionWaitGroup.Done()
}
},
}
listener, err := net.Listen("tcp", s.address)
if err != nil {
return err
}
serverErrChan := make(chan error, 1)
go func() {
serverErrChan <- server.Serve(listener)
}()
close(ready)
for {
select {
case err = <-serverErrChan:
return err
case <-signals:
close(s.stoppingChan)
listener.Close()
s.inactiveConnectionsMu.Lock()
for c := range s.inactiveConnections {
c.Close()
}
s.inactiveConnectionsMu.Unlock()
s.connectionWaitGroup.Wait()
return nil
}
}
}
func (s *httpServer) addInactiveConnection(conn net.Conn) {
select {
case <-s.stoppingChan:
conn.Close()
default:
s.inactiveConnectionsMu.Lock()
s.inactiveConnections[conn] = struct{}{}
s.inactiveConnectionsMu.Unlock()
}
}
func (s *httpServer) removeInactiveConnection(conn net.Conn) {
s.inactiveConnectionsMu.Lock()
delete(s.inactiveConnections, conn)
s.inactiveConnectionsMu.Unlock()
}