snippetgoModeratepending
Go HTTP server with graceful shutdown
Viewed 0 times
graceful shutdownsignal handlinghttp.ServercontextSIGTERMShutdown
linuxmacos
Problem
Go HTTP server needs to shut down gracefully — finish serving in-flight requests before exiting. Default http.ListenAndServe stops abruptly on SIGTERM, dropping active connections.
Solution
HTTP server with context-based graceful shutdown, signal handling, and configurable timeout.
Code Snippets
HTTP server with signal handling and graceful shutdown
package main
import (
"context"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("ok"))
})
srv := &http.Server{
Addr: ":8080",
Handler: mux,
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
IdleTimeout: 120 * time.Second,
}
// Start server in goroutine
go func() {
log.Printf("Listening on %s", srv.Addr)
if err := srv.ListenAndServe(); err != http.ErrServerClosed {
log.Fatalf("Server error: %v", err)
}
}()
// Wait for interrupt signal
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
log.Println("Shutting down...")
// Graceful shutdown with timeout
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
log.Fatalf("Forced shutdown: %v", err)
}
log.Println("Server stopped")
}Revisions (0)
No revisions yet.