How do you handle HTTP server shutdown gracefully in Go?
In Go, you can handle HTTP server shutdown gracefully by using the http.Server's Shutdown() method. This method provides a way to gracefully shut down the server by allowing it to finish handling any active requests before closing all connections.
HTTP server shutdown gracefully
Here's an example code that demonstrates how to gracefully shutdown an HTTP server in Go:
Example
package main
import (
"context"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)
func main() {
// Create a new HTTP server
srv := &http.Server{
Addr: ":8080",
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Simulate a long-running request
time.Sleep(10 * time.Second)
w.Write([]byte("Hello, World!"))
}),
}
// Create a channel to receive signals
signalCh := make(chan os.Signal, 1)
signal.Notify(signalCh, syscall.SIGINT, syscall.SIGTERM)
// Start the server in a separate goroutine
go func() {
log.Printf("Server listening on %s\n", srv.Addr)
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("listen: %s\n", err)
}
}()
// Wait for a signal to shutdown the server
sig := <-signalCh
log.Printf("Received signal: %v\n", sig)
// Create a context with a timeout
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
// Shutdown the server gracefully
if err := srv.Shutdown(ctx); err != nil {
log.Fatalf("Server shutdown failed: %v\n", err)
}
log.Println("Server shutdown gracefully")
}
In this example, we create a new HTTP server and start it in a separate goroutine. We also create a channel to receive signals, and we wait for a signal to shutdown the server. When a signal is received, we create a context with a timeout and call the Shutdown() method on the server. If the server is still handling requests after the timeout, it will forcefully terminate all active connections.
Note that if you have any resources that need to be cleaned up before the server shuts down, you should include them in the Shutdown() function. This will ensure that they are cleaned up before the server terminates.
Most Helpful This Week
Example: Fields and FieldsFunc from BYTES PackageGet Year, Month, Day, Hour, Min and Second from current date and time.Golang Slice interface and array concatenationHow to Convert string to integer type in Go?Example of Switch Case with Break in For LoopSplit a character string based on change of characterHow to rotate an image?How to append text to a file in Golang?How to check if a string contains a substring in Golang?Regex to extract image name from HTML in Golang