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 handle HTTP authentication with an HTTP client in Go?
How do you read cookies in an HTTP request with an HTTP client in Go?
How do you read headers from an HTTP response with an HTTP client in Go?
What is an HTTP server in Go?
How do you create an HTTP client in Go?
How do you handle HTTP timeouts with an HTTP client in Go?
Most Helpful This Week
How pointer & and * and ** works in Golang?Regular expression to validate common Credit Card NumbersSimple function with return value in GolangConstructors in GolangExample: How to use TeeReader from IO Package in Golang?Convert Int data type to Int16 Int32 Int64Normal function parameter with variadic function parameterHow to fetch an Integer variable as String in Go?How To Make an HTTP Server in Golang?How to delete or remove element from a Map?