Skip to content

Instantly share code, notes, and snippets.

@as
Created April 3, 2020 19:21
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 as/9ddda867fb3f132ddcd39cc5c7baf8f2 to your computer and use it in GitHub Desktop.
Save as/9ddda867fb3f132ddcd39cc5c7baf8f2 to your computer and use it in GitHub Desktop.
// install the signal handler
sigs, sigdone := make(chan os.Signal, 2), make(chan bool)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
go func() {
<-sigs
close(sigdone)
}()
// install the workers
teardown := make(chan bool)
workerdone := make(chan bool)
go func() { <-teardown }()
// install the server
srv := &http.Server{}
srvdone := make(chan bool)
go func() {
srv.ListenAndServe()
close(srvdone)
}()
// wait for something to happen
select {
case <-sigdone:
case <-srvdone:
}
// stop server
ctx, fn := context.WithTimeout(context.Background(), time.Second)
srv.Shutdown(ctx)
fn()
close(teardown) // stop workers
// dont wait forever
select {
case <-time.After(time.Second):
case <-workerdone:
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment