Skip to content

Commit

Permalink
First try to implement graceful shutdown on the server. Stops listeni…
Browse files Browse the repository at this point in the history
…ng but does not interrupt any active connections. todo unit tests
  • Loading branch information
rvflash committed Sep 2, 2019
1 parent 8a573bd commit d2ebeb4
Showing 1 changed file with 19 additions and 26 deletions.
45 changes: 19 additions & 26 deletions server.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,62 +130,55 @@ const network = "tcp"

// Run starts listening on TCP address.
// This method will block the calling goroutine indefinitely unless an error happens.
func (s *Server) Run(addr string) (err error) {
func (s *Server) Run(addr string) error {
l, err := net.Listen(network, addr)
if err != nil {
return
return err
}
defer func() {
cErr := l.Close()
if err != nil {
err = cErr
}
}()
err = s.serve(l)
return
return s.serve(l)
}

// RunTLS acts identically to the Run method, except that it uses the TLS protocol.
// This method will block the calling goroutine indefinitely unless an error happens.
func (s *Server) RunTLS(addr, certFile, keyFile string) (err error) {
func (s *Server) RunTLS(addr, certFile, keyFile string) error {
c, err := tlsConfig(certFile, keyFile)
if err != nil {
return
return err
}
l, err := tls.Listen(network, addr, c)
if err != nil {
return
return err
}
defer func() {
cErr := l.Close()
if err != nil {
err = cErr
}
}()
err = s.serve(l)
return
return s.serve(l)
}

func (s *Server) serve(l net.Listener) error {
func (s *Server) serve(l net.Listener) (err error) {
var (
w8 sync.WaitGroup
ctx context.Context
)
ctx, s.cancel = context.WithCancel(context.Background())
defer s.cancel()
defer func() {
s.cancel()
cErr := l.Close()
if err != nil {
err = cErr
}
}()
for {
select {
case <-s.shutdown:
// Stops listening but does not interrupt any active connections.
// See the Shutdown method to gracefully shuts down the server.
w8.Wait()
close(s.closed)
return nil
return
default:
}
c, err := read(l, s.ReadTimeout)
var c net.Conn
c, err = read(l, s.ReadTimeout)
if err != nil {
return err
return
}
rwc := s.newConn(c)
w8.Add(1)
Expand Down

0 comments on commit d2ebeb4

Please sign in to comment.