Skip to content

Instantly share code, notes, and snippets.

@DavadDi
Last active January 23, 2018 09:55
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 DavadDi/4048e796873205296802e21e34dc0325 to your computer and use it in GitHub Desktop.
Save DavadDi/4048e796873205296802e21e34dc0325 to your computer and use it in GitHub Desktop.
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
Copy link
Author

DavadDi 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