-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
128 lines (115 loc) · 2.45 KB
/
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
package cherry
import (
"crypto/tls"
"errors"
"net"
"net/http"
"os"
"os/signal"
"strings"
"sync"
"syscall"
"time"
"github.com/bradfitz/http2"
)
const useClosedConn = "use of closed network connection"
// Server provides a gracefull shutdown of http server.
type server struct {
*http.Server
quit chan struct{}
fquit chan struct{}
wg sync.WaitGroup
}
func newServer(addr string, h http.Handler, HTTP2 bool) *http.Server {
srv := &http.Server{
Addr: addr,
Handler: h,
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
}
if HTTP2 {
http2.ConfigureServer(srv, &http2.Server{})
}
return srv
}
func (s *server) ListenAndServe() error {
l, err := net.Listen("tcp", s.Addr)
if err != nil {
return err
}
return s.serve(l)
}
func (s *server) ListenAndServeTLS(cert, key string) error {
var err error
config := &tls.Config{}
if s.TLSConfig != nil {
*config = *s.TLSConfig
}
if config.NextProtos == nil {
config.NextProtos = []string{"http/1.1"}
}
config.Certificates = make([]tls.Certificate, 1)
config.Certificates[0], err = tls.LoadX509KeyPair(cert, key)
if err != nil {
return err
}
l, err := net.Listen("tcp", s.Addr)
if err != nil {
return err
}
tlsList := tls.NewListener(l.(*net.TCPListener), config)
return s.serve(tlsList)
}
// serve hooks in the Server.ConnState to incr and decr the waitgroup based on
// the connection state.
func (s *server) serve(l net.Listener) error {
s.Server.ConnState = func(conn net.Conn, state http.ConnState) {
switch state {
case http.StateNew:
s.wg.Add(1)
case http.StateClosed, http.StateHijacked:
s.wg.Done()
}
}
go s.closeNotify(l)
errChan := make(chan error, 1)
go func() {
errChan <- s.Server.Serve(l)
}()
for {
select {
case err := <-errChan:
if strings.Contains(err.Error(), useClosedConn) {
continue
}
return err
case <-s.quit:
s.SetKeepAlivesEnabled(false)
s.wg.Wait()
return errors.New("server stopped gracefully")
case <-s.fquit:
return errors.New("server stopped: process killed")
}
}
}
func (s *server) closeNotify(l net.Listener) {
sig := make(chan os.Signal, 1)
signal.Notify(
sig,
syscall.SIGTERM,
syscall.SIGQUIT,
syscall.SIGUSR2,
syscall.SIGINT,
)
sign := <-sig
switch sign {
case syscall.SIGTERM, syscall.SIGQUIT, syscall.SIGINT:
l.Close()
s.quit <- struct{}{}
case syscall.SIGKILL:
l.Close()
s.fquit <- struct{}{}
case syscall.SIGUSR2:
panic("USR2 => not implemented")
}
}