Practical Examples
Web Server Graceful Shutdown
package main
import (
"context"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)
func main() {
server := &http.Server{Addr: ":8080"}
// Start HTTP server
go func() {
if err := server.ListenAndServe(); err != http.ErrServerClosed {
log.Fatalf("HTTP server error: %v", err)
}
}()
// Signal handling
stopChan := make(chan os.Signal, 1)
signal.Notify(stopChan, syscall.SIGINT, syscall.SIGTERM)
<-stopChan
log.Println("Shutting down server...")
// Graceful shutdown with timeout
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := server.Shutdown(ctx); err != nil {
log.Fatalf("Server shutdown error: %v", err)
}
log.Println("Server stopped")
}
Signal Handling Workflow
graph TD
A[Server Running] --> B[Signal Received]
B --> C[Stop Accepting New Connections]
C --> D[Complete Existing Requests]
D --> E[Graceful Shutdown]
E --> F[Server Stops]
Background Task Management
package main
import (
"fmt"
"os"
"os/signal"
"sync"
"syscall"
"time"
)
func backgroundTask(id int, stopChan <-chan struct{}, wg *sync.WaitGroup) {
defer wg.Done()
ticker := time.NewTicker(1 * time.Second)
defer ticker.Stop()
for {
select {
case <-ticker.C:
fmt.Printf("Task %d running...\n", id)
case <-stopChan:
fmt.Printf("Task %d stopping...\n", id)
return
}
}
}
func main() {
// Cancellation mechanism
stopChan := make(chan struct{})
signalChan := make(chan os.Signal, 1)
signal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM)
// WaitGroup for task synchronization
var wg sync.WaitGroup
// Start multiple background tasks
for i := 0; i < 3; i++ {
wg.Add(1)
go backgroundTask(i, stopChan, &wg)
}
// Wait for termination signal
<-signalChan
close(stopChan)
// Wait for all tasks to complete
wg.Wait()
fmt.Println("All tasks stopped")
}
Signal Handling Scenarios
Scenario |
Signal |
Action |
Web Server Shutdown |
SIGTERM |
Stop accepting new connections |
Long-Running Process |
SIGINT |
Save state and exit |
Resource Cleanup |
SIGKILL |
Immediate termination |
Key Takeaways
- Use context for timeout management
- Implement clean shutdown mechanisms
- Handle multiple concurrent tasks
- Provide graceful degradation
At LabEx, we recommend comprehensive signal handling to build robust Go applications that respond elegantly to system interrupts.