Skip to content

Commit 2a079b7

Browse files
author
Mike Heffner
authored
Merge pull request #110 from netlify/fix/connection-draining
Wait for connections to drain.
2 parents ab85811 + d709024 commit 2a079b7

File tree

1 file changed

+14
-6
lines changed

1 file changed

+14
-6
lines changed

server/server.go

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,10 @@ import (
1616
// Server handles the setup and shutdown of the http server
1717
// for an API
1818
type Server struct {
19-
log logrus.FieldLogger
20-
svr *http.Server
21-
api APIDefinition
19+
log logrus.FieldLogger
20+
svr *http.Server
21+
api APIDefinition
22+
done chan (bool)
2223
}
2324

2425
type Config struct {
@@ -62,7 +63,8 @@ func New(log logrus.FieldLogger, projectName string, config Config, api APIDefin
6263
Addr: fmt.Sprintf(":%d", config.Port),
6364
Handler: r,
6465
},
65-
api: api,
66+
api: api,
67+
done: make(chan bool),
6668
}
6769

6870
if config.TLS.Enabled {
@@ -80,6 +82,8 @@ func New(log logrus.FieldLogger, projectName string, config Config, api APIDefin
8082
func (s *Server) Shutdown(to time.Duration) error {
8183
ctx, cancel := context.WithTimeout(context.Background(), to)
8284
defer cancel()
85+
defer close(s.done)
86+
8387
if err := s.svr.Shutdown(ctx); err != nil && err != http.ErrServerClosed {
8488
return err
8589
}
@@ -95,9 +99,13 @@ func (s *Server) ListenAndServe() error {
9599
} else {
96100
err = s.svr.ListenAndServe()
97101
}
102+
// Now that server is no longer listening
103+
s.log.Info("Listener shutdown, waiting for connections to drain")
104+
105+
// Wait until Shutdown returns
106+
<-s.done
98107

99-
// Now that server is no longer listening, shutdown the API
100-
s.log.Info("Listener shutdown, stopping API")
108+
s.log.Info("Connections are drained, shutting down API")
101109

102110
s.api.Stop()
103111

0 commit comments

Comments
 (0)