Home  >  Article  >  Backend Development  >  How to shut down HTTP server gracefully in Golang

How to shut down HTTP server gracefully in Golang

PHPz
PHPzOriginal
2023-03-22 14:23:502184browse

Golang (also known as Go) is a relatively young programming language that is widely used in the development of back-end services and APIs. HTTP is a commonly used protocol, and many Golang developers choose to use the HTTP package that comes with Golang to develop HTTP servers. However, we encounter some problems when we need to shut down the HTTP server. In this article, we will explain how to shut down an HTTP server gracefully in Golang.

  1. HTTP server shutdown method

In Golang, we usually use the http.ListenAndServe() function to start the HTTP server. This function will run until the program is killed or the server is shut down. If we simply close the program, the HTTP server will stop running immediately. However, this method is not a graceful shutdown because the client being processed will be forced to disconnect, which may result in data loss or exceptions.

Another way to close is to use the Done() method of the server context (context). When we call the Done() method, the HTTP server properly shuts down and stops accepting new client connections, but will still handle some already accepted connections. Although this will not force the connection of the client being processed, it may still cause some requests to become unresponsive.

Finally, we have an elegant way to shut down, which is to use the Shutdown() method in the http.Server structure. This method gracefully shuts down the HTTP server by waiting for the request being processed to complete before shutting down the server.

  1. Achieving graceful shutdown of the HTTP server

Assume that we have written the following code to start the HTTP server:

package main

import (
    "log"
    "net/http"
)

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("Hello World!"))
    })

    if err := http.ListenAndServe(":8080", nil); err != nil {
        log.Fatal(err)
    }
}

Now we need to properly close the HTTP server when the program exits. We can take the following steps:

1) Create an http.Server instance and set the Handler property of the instance to our existing Handler function.

server := http.Server{
    Addr:    ":8080",
    Handler: http.DefaultServeMux,
}

2) Use a goroutine to start the ListenAndServe() method of http.Server to handle client connection requests.

go func() {
    if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
        log.Fatal(err)
    }
}()

3) Use the Shutdown() method of http.Server to safely shut down the server when our program exits.

// 用于停止 HTTP 服务器的通道
stopChan := make(chan os.Signal)

// 监听 Interrupt 和 Terminate 信号
signal.Notify(stopChan, os.Interrupt, syscall.SIGTERM)

// 等待接收到信号,执行 Shutdown()
<-stopChan
log.Println("Shutting down server...")

// 等待处理完成的请求处理完成
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

if err := server.Shutdown(ctx); err != nil {
    log.Fatal(err)
}

log.Println("Server gracefully stopped.")

In this code we first create a channel to listen for interrupt or termination signals sent by the operating system (such as Ctrl C). Then we wait for the signal to be received and execute the Shutdown() method. Before calling the Shutdown() method, we use context.WithTimeout() to create a context (Context) to wait for the request being processed to complete within the specified timeout period. The Shutdown() method safely shuts down the HTTP server after all requests have been processed.

  1. Summary

This article introduces how to gracefully shut down the HTTP server in Golang. Use the Shutdown() method of http.Server to shut down the HTTP server gracefully and avoid data loss or exceptions caused by forced disconnection.

It should be noted that if there are already connections being processed by the client and the server, the shutdown of the server will need to wait for these connections to be processed before it can be closed normally. Therefore, to be more sure of a complete shutdown, we can use context.WithTimeout() to set a timeout to wait for the request being processed to complete before calling the Shutdown() method.

I hope this article can help Golang developers when developing HTTP servers.

The above is the detailed content of How to shut down HTTP server gracefully in Golang. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn