Skip to content

Instantly share code, notes, and snippets.

@lionello
Created August 20, 2018 06:20
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 lionello/c1d8914a2a77a2d73098cb212d7d6a00 to your computer and use it in GitHub Desktop.
Save lionello/c1d8914a2a77a2d73098cb212d7d6a00 to your computer and use it in GitHub Desktop.
Graceful shutdown of a Go HTTP server
package main
import (
"context"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)
func main() {
srv := &http.Server{Addr: ":8080"}
idleConnsClosed := make(chan struct{})
go func() {
stopChan := make(chan os.Signal, 1)
// subscribe to SIGINT and SIGTERM signals
signal.Notify(stopChan, syscall.SIGINT, syscall.SIGTERM)
// wait for SIGINT
<-stopChan
log.Println("Shutting down server...")
// shut down gracefully, but wait no longer than 5 seconds before halting
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// We received an interrupt signal, shut down.
if err := srv.Shutdown(ctx); err != nil {
// Error from closing listeners, or context timeout:
log.Printf("HTTP server Shutdown: %v", err)
}
// Unblock the main function
close(idleConnsClosed)
}()
log.Println("Listening on", srv.Addr)
// service connections
if err := srv.ListenAndServe(); err != http.ErrServerClosed {
// Error starting or closing listener:
log.Panicf("HTTP server ListenAndServe: %v", err)
}
<-idleConnsClosed
log.Println("Server gracefully stopped")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment