Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
go_1.8_http_graceful_shutdown
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)
}
}
@DavadDi

This comment has been minimized.

Copy link
Owner Author

commented Feb 22, 2017

d := time.Now().Add(5 * time.Second) 
ctx, cancel := context.WithDeadline(context.Background(), d)

defer cancel()

   if err := srv.Shutdown(ctx)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.