Last active
January 23, 2018 09:55
-
-
Save DavadDi/4048e796873205296802e21e34dc0325 to your computer and use it in GitHub Desktop.
go_1.8_http_graceful_shutdown
This file contains hidden or 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" | |
"fmt" | |
"html" | |
"log" | |
"net/http" | |
"os" | |
"os/signal" | |
) | |
func main() { | |
// subscribe to SIGINT signals | |
quit := make(chan os.Signal) | |
signal.Notify(quit, os.Interrupt,syscall.SIGINT) | |
srv := &http.Server{Addr: ":8080", Handler: http.DefaultServeMux} | |
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { | |
fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path)) | |
}) | |
go func() { | |
err := srv.ListenAndServe() | |
if err != http.ErrServerClosed { | |
log.Errf("listen: %s\n", err) | |
} | |
quit <- syscall.SIGINT | |
} | |
<-quit | |
// When Shutdown is called, Serve, ListenAndServe, | |
// and ListenAndServeTLS immediately return ErrServerClosed. | |
// Make sure the program doesn't exit and waits instead for Shutdown to return. | |
log.Println("Shutting down server...") | |
if err := srv.Shutdown(context.Background()); err != nil { | |
log.Errf("could not shutdown: %v", err) | |
} | |
} |
Author
DavadDi
commented
Feb 22, 2017
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment