graceful shutdown for http server on linux
When running an http server, it is often necessary to perform certain operations before the server exits. This can be done using the Unix signal mechanism.
One way to do this is to use the os.Signal package in Go:
package main import ( "fmt" "log" "net/http" "os" "os/signal" ) func main() { // Create a new http server. http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello, World!") }) go func() { // Start the server. log.Fatal(http.ListenAndServe(":8080", nil)) }() // Create a channel to receive os signals. sigchan := make(chan os.Signal) signal.Notify(sigchan, os.Interrupt) // Block until a signal is received. <-sigchan // Perform shutdown operations. log.Println("Shutting down server...") // Close the server. err := http.CloseServer(http.DefaultServer) if err != nil { log.Fatal(err) } // Exit the program. os.Exit(0) }
This code will create a new http server and listen on port 8080. When the program receives an interrupt signal (e.g., Ctrl C), it will perform the shutdown operations, which in this case include closing the server and exiting the program.
The above is the detailed content of How to Implement Graceful Shutdown for an HTTP Server on Linux?. For more information, please follow other related articles on the PHP Chinese website!