In Go, managing server shutdown and cleanup typically involves calling methods like Shutdown and Close on an HTTP server. Here's a breakdown of the two methods:
1. Server.Shutdown(ctx context.Context)
Gracefully shuts down the server without interrupting any active connections.
Waits for the ongoing requests to finish within the provided context timeout.
Useful when you want a clean shutdown, ensuring all ongoing processes complete gracefully.
2. Server.Close()
Immediately closes all active connections and stops the server.
Does not wait for active requests to complete.
Use this when you need an abrupt stop of the server.
Key Differences
Aspect Shutdown Close
Graceful Termination Yes No
Context Support Yes No
Ongoing Requests Waits to complete Terminates immediately
Example Implementation
Below is an example illustrating the use of Shutdown and Close in a Go HTTP server:
go
Copy code
package main
import (
"context"
"fmt"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)
func main() {
// Create a new HTTP server
server := &http.Server{
Addr: ":8080",
Handler: http.HandlerFunc(handler),
}
// Channel to listen for OS signals
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
// Run the server in a separate goroutine
go func() {
fmt.Println("Starting server on :8080")
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
fmt.Printf("Server error: %v\n", err)
}
}()
// Wait for OS signal to quit
<-quit
fmt.Println("\nShutting down server...")
// Graceful shutdown
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := server.Shutdown(ctx); err != nil {
fmt.Printf("Shutdown error: %v\n", err)
} else {
fmt.Println("Server shut down gracefully")
}
// Optional: Force close if shutdown takes too long
select {
case <-ctx.Done():
if ctx.Err() == context.DeadlineExceeded {
fmt.Println("Forced close due to timeout")
server.Close()
}
}
}
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, world!")
}
Explanation of the Code
signal.Notify: Captures SIGINT or SIGTERM signals to initiate shutdown.
Graceful Shutdown: The Shutdown method waits for ongoing requests to finish within a specified timeout.
Forced Close: If shutdown exceeds the timeout, Close is called to terminate immediately.
This ensures your server can handle both graceful shutdowns and abrupt terminations effectively.
You said:
what version comes with server::shutdown
ChatGPT said:
ChatGPT
The Server.Shutdown method was introduced in Go 1.8 as part of the net/http package. This version added support for gracefully shutting down an HTTP server.
Key Notes
Go 1.8 was released in February 2017.
No comments:
Post a Comment