Created
August 20, 2018 06:20
-
-
Save lionello/c1d8914a2a77a2d73098cb212d7d6a00 to your computer and use it in GitHub Desktop.
Graceful shutdown of a Go HTTP server
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" | |
"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