Graceful HTTP Server Shutdown
Listen for termination signals and shut an HTTP server down gracefully so in-flight requests finish before the process exits.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.Accept Header ParserParse an Accept header into media ranges with their quality values and specificity, sorted by preference for content negotiation debugging.Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.
FAQ
- How do you run Graceful HTTP Server Shutdown?
- It runs as-is — treat the file as the whole program and execute it.
Report a problem with this exampleOpens a pre-filled issue on GitHub.