Golang is a very popular programming language with efficient concurrent processing capabilities and excellent performance. I believe many golang developers will encounter such a problem, how to gracefully shut down the http service in golang?
First of all, we need to know that it is relatively easy to create an http service. It only requires a few lines of code. For example, the following is a simple example:
package main import ( "fmt" "net/http" ) func main() { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "Hello") }) http.ListenAndServe(":8080", nil) }
Here we create a new http service, listen to the local port 8080, and return a "Hello" for each visit. But how to shut down this service gracefully?
The common method is to use os.Signal to manage the life cycle of the service. os.Signal is an interrupt signal sent by the operating system to the process, such as Ctrl C, etc., with the purpose of requiring the program to terminate execution. In golang, we can listen to these signals and then execute some hook functions after receiving the signal to shut down the http service gracefully.
The specific implementation is as follows:
package main import ( "context" "fmt" "net/http" "os" "os/signal" "syscall" "time" ) func main() { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "Hello") }) srv := &http.Server{Addr: ":8080"} signalChan := make(chan os.Signal, 1) signal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM) go func() { sig := <-signalChan fmt.Printf("Signal Received: %s, Gracefully shutting down...\n", sig) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() srv.Shutdown(ctx) }() fmt.Println("Server starting...") if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed { fmt.Printf("server start failed, err: %v\n", err) return } fmt.Println("Server closed.") }
We registered two signals through the signal.Notify method, namely Ctrl C and kill. Then, wait for the arrival of the signal through an infinite loop in the main function. When the signal arrives, we will first print a line of log, indicating that we successfully received a signal, and then we will call the Shutdown() method of http.Server to shut down the http service normally. These operations will be performed in the context.
When we pass a context.Context object to the Shutdown() method of http.Server, the http service will enter the process of graceful shutdown. The specific process of the Shutdown() method is as follows:
That is to say, after the Shutdown() method is called, all active connections will be closed immediately, and new connection requests will also be prohibited. Then, the Shutdown() method will call the Shutdown() method of all active connections to close the connection, so that we can ensure that all connections are closed normally. Finally, the Shutdown() method will close our http server. After the shutdown is completed, the program will exit.
Through this graceful shutdown method, we can ensure that the http service will not affect the request being processed when it is shut down. Even if you call Ctrl C when completing the HTTP request, it will not affect the performance of the HTTP connection. Doing so can make our programs more robust and reliable, making them ideal for use in production environments.
Of course, this is just an example of golang closing the http service gracefully. You can modify it according to your actual environment. I hope this article can help you.
The above is the detailed content of Analyze how to gracefully shut down the http service in golang. For more information, please follow other related articles on the PHP Chinese website!