Sobes.tech
Senior

How should an HTTP server in Go be designed to support graceful shutdown and proper resource cleanup?

sobes.tech AI

Answer from AI

To support graceful shutdown in an HTTP server in Go, you need to use a context with cancellation and the Shutdown method from the net/http package. This allows the server to properly finish handling current requests and release resources before stopping.

Example:

srv := &http.Server{Addr: ":8080", Handler: myHandler}

// Run the server in a separate goroutine
go func() {
    if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
        log.Fatalf("ListenAndServe(): %v", err)
    }
}()

// Wait for the termination signal
quit := make(chan os.Signal, 1)
signal.Notify(quit, os.Interrupt, syscall.SIGTERM)
<-quit

// Create a context with a timeout for shutdown
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

// Call Shutdown for graceful stop
if err := srv.Shutdown(ctx); err != nil {
    log.Fatalf("Server Shutdown Failed:%+v", err)
}

log.Println("Server exited properly")

This approach guarantees that the server will not interrupt active connections but will properly close them, free resources, and shut down.

How should an HTTP server in Go be designed to… - sobes.tech