Lesson 27 of 60 · Go
Graceful Shutdown of Servers
Duration: 15 minutes
Graceful Shutdown
This lesson explains the main concept clearly with beginner-friendly examples and background so you can learn why the code works.
Handle termination signals to allow inflight requests to finish.
srv := &http.Server{ Addr: ":8080", Handler: mux }
go func() { log.Fatal(srv.ListenAndServe()) }()
quit := make(chan os.Signal, 1)
signal.Notify(quit, os.Interrupt, syscall.SIGTERM)
<-quit
log.Println("shutting down server…")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil { log.Fatalf("forced shutdown: %v", err) }
log.Println("server stopped")