Graceful HTTP shutdown in Go
GoPublic
func main() {
srv := &http.Server{Addr: ":8080", Handler: routes()}
go func() {
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("listen: %v", err)
}
}()
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
log.Fatalf("forced shutdown: %v", err)
}
}Comments(1)
@maya_dev6d ago
This is the exact pattern I use in production. Solid.