Skip to content

Instantly share code, notes, and snippets.

@ash2k
Last active February 14, 2018 20:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ash2k/2ce1579cc6502e20ce2b4a78e447d87f to your computer and use it in GitHub Desktop.
Save ash2k/2ce1579cc6502e20ce2b4a78e447d87f to your computer and use it in GitHub Desktop.
Clean shutdown of Go http server
func startStopServer(ctx context.Context, srv *http.Server, shutdownTimeout time.Duration) error {
var wg sync.WaitGroup
defer wg.Wait() // wait for goroutine to shutdown active connections
ctx, cancel := context.WithCancel(ctx)
defer cancel()
wg.Add(1)
go func() {
defer wg.Done()
<-ctx.Done()
c, cancel := context.WithTimeout(context.Background(), shutdownTimeout)
defer cancel()
if srv.Shutdown(c) != nil {
srv.Close()
}
}()
err := srv.ListenAndServe()
if err != http.ErrServerClosed {
// Failed to start or dirty shutdown
return err
}
// Clean shutdown
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment