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 to slice elements in Golang?
10 Countries Paying Highest Salaries to Cybersecurity Professionals
Invalid operation: <variable> (type <type>) does not support indexing error in Golang
Go program to find TXT records of a domain
Struct Instantiation Using Pointer Address Operator
Golang program for implementation of Binary Search
Most Helpful This Week
Example: ReadAll, ReadDir, and ReadFile from IO PackageWhat is GOPATH?How to declare empty Map in Go?How to check if a string contains a numbers in Golang?Example: Arrays of Arrays, Arrays of Slices, Slices of Arrays and Slices of SlicesHow to fix race condition using Atomic Functions in Golang?How to Remove duplicate values from Slice?How to extract text from between html tag using Regular Expressions in Golang?How to import structs from another package in Go?How to Convert string to float type in Go?