Created
August 19, 2018 03:34
-
-
Save dhl/feb5d152325e622d5630a01560b51437 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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