Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons

© 2026 BraveProgrammer. All rights reserved.

  1. Courses
  2. /
  3. Go Programming Bootcamp

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")

Info

Always give your server a timeout; otherwise a hung connection can block shutdown indefinitely.

Previous: Logging with `log` and Structured Logging (`zap`)Next: Reflection with the `reflect` Package