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
How do you create an HTTP server in Go?
How do you handle HTTP timeouts with an HTTP client in Go?
How do you send an HTTP PATCH request in Go?
How do you handle HTTP client caching in Go?
How do you read headers from an HTTP response with an HTTP client in Go?
What is the default HTTP server in Go?
How do you create an HTTP client in Go?
How do you handle HTTP requests in Go?
How do you handle HTTP client server alerting in Go?
How do you handle HTTP errors in Go?
Most Helpful This Week
How to blur an image in Golang?Convert Float32 to Float64 and Float64 to Float32How to read current directory using Readdir?How to trim leading and trailing white spaces of a string in Golang?Dereferencing a pointer from another packageHow to update content of a text file?Regular expression to extract all Non-Alphanumeric Characters from a StringReplace any non-alphanumeric character sequences with a dash using RegexVarious examples of printing and formatting in GolangHow to include and execute HTML template?