Graceful HTTP Server Shutdown

Listen for termination signals and shut an HTTP server down gracefully so in-flight requests finish before the process exits.

GoResilience

Code

gosnippet
31 lines
package main

import (
	"context"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"
)

func main() {
	server := &http.Server{Addr: ":8080", Handler: http.NewServeMux()}
	go func() {
		if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Fatalf("listen: %v", err)
		}
	}()

	stop := make(chan os.Signal, 1)
	signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM)
	<-stop

	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	if err := server.Shutdown(ctx); err != nil {
		log.Fatalf("shutdown: %v", err)
	}
	log.Println("server stopped cleanly")
}

How it works

Graceful HTTP Server Shutdown comes down to the function main.

Nothing falls through silently — 2 checkpoints test err != nil on the way through. Work runs on a goroutine and results come back through a channel, giving a safe handoff between the two execution contexts. defer inverts the usual order — register now, run at return — which is why cleanup cannot be skipped.

Statements that matter

ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
stop := make(chan os.Signal, 1)
defer cancel()

Interactive Tools for This Topic

FAQ

How do you run Graceful HTTP Server Shutdown?
It runs as-is — treat the file as the whole program and execute it.