Skip to content

Instantly share code, notes, and snippets.

@dhl
Created August 19, 2018 03:34
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 dhl/feb5d152325e622d5630a01560b51437 to your computer and use it in GitHub Desktop.
Save dhl/feb5d152325e622d5630a01560b51437 to your computer and use it in GitHub Desktop.
package main
import (
"context"
"log"
"net/http"
"os"
"os/signal"
"time"
)
func main() {
// subscribe to SIGINT signals
stopChan := make(chan os.Signal)
signal.Notify(stopChan, os.Interrupt)
mux := http.NewServeMux()
mux.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
time.Sleep(5 * time.Second)
w.Write([]byte("Finished!\n"))
}))
srv := &http.Server{Addr: ":8081", Handler: mux}
go func() {
// service connections
if err := srv.ListenAndServe(); err != nil {
log.Printf("listen: %s\n", err)
stopChan <- os.Interrupt
}
}()
<-stopChan // wait for SIGINT
log.Println("Shutting down server...")
// shut down gracefully, but wait no longer than 5 seconds before halting
ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
srv.Shutdown(ctx)
log.Println("gracefully stopped stopped")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment