Lesson 27 of 60
GoGraceful Shutdown of Servers
15 minutes
Course progress45%
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( os.Signal, )
signal.Notify(quit, os.Interrupt, syscall.SIGTERM)
<-quit
log.Println()
ctx, cancel := context.WithTimeout(context.Background(), *time.Second)
cancel()
err := srv.Shutdown(ctx); err != { log.Fatalf(, err) }
log.Println()