package main import ( "context" "fmt" "log" "net/http" "os" "os/signal" "syscall" "time" ) func main() { // Create a server server := &http.Server{Addr: ":8080", Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { time.Sleep(2 * time.Second) // Simulate a long-running request fmt.Fprintf(w, "Hello from graceful server! ") })} // Channel to listen for OS signals quit := make(chan os.Signal, 1) signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM) // Start server in a goroutine go func() { fmt.Println("Server started on :8080") if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed { log.Fatalf("Server failed: %v", err) } }() // Block until we receive our signal <-quit fmt.Println("Shutting down server...") // Create a context with a timeout for shutdown ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() // Attempt to gracefully shut down if err := server.Shutdown(ctx); err != nil { log.Fatalf("Server shutdown failed: %v", err) } fmt.Println("Server gracefully stopped.") }