-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathwebserver_serve.go
65 lines (50 loc) · 1.34 KB
/
webserver_serve.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
package go_webserver
import (
"context"
"net"
"sync/atomic"
"time"
)
// -----------------------------------------------------------------------------
const (
stateNotStarted = 1
stateStarting = 2
stateRunning = 3
stateStopping = 4
stateStopped = 5
)
const (
shutdownTimeout = 5 * time.Second
)
// -----------------------------------------------------------------------------
func (srv *Server) serve(ln net.Listener) {
ch := make(chan error, 1)
go func(ln net.Listener) {
ch <- srv.fastserver.Serve(ln)
}(ln)
// Set new state
srv.setState(stateRunning)
// Run in background until shutdown or error
go srv.serveLoop(ch)
}
func (srv *Server) serveLoop(ch chan error) {
select {
case err := <-ch:
srv.setState(stateStopping)
// Web server is no longer able to accept more connections
if srv.listenErrorHandler != nil && err != nil {
srv.listenErrorHandler(srv, err)
}
// handle termination signal
case <-srv.startShutdownSignal:
srv.setState(stateStopping)
// Attempt the graceful shutdown by closing the listener and completing all inflight requests.
ctx, ctxCancel := context.WithTimeout(context.Background(), shutdownTimeout)
_ = srv.fastserver.ShutdownWithContext(ctx)
ctxCancel()
}
srv.setState(stateStopped)
}
func (srv *Server) setState(newState int32) {
atomic.StoreInt32(&srv.state, newState)
}