search
HomeBackend DevelopmentGolangHow to shut down HTTP server gracefully in Golang

How to shut down HTTP server gracefully in Golang

Mar 22, 2023 pm 02:23 PM
httpgolanggo language

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()
<p>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. </p><ol start="3"><li><strong>Summary</strong></li></ol><p>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. </p><p>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. </p><p>I hope this article can help Golang developers when developing HTTP servers. </p>

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
Learn Go Binary Encoding/Decoding: Working with the 'encoding/binary' PackageLearn Go Binary Encoding/Decoding: Working with the 'encoding/binary' PackageMay 08, 2025 am 12:13 AM

Go uses the "encoding/binary" package for binary encoding and decoding. 1) This package provides binary.Write and binary.Read functions for writing and reading data. 2) Pay attention to choosing the correct endian (such as BigEndian or LittleEndian). 3) Data alignment and error handling are also key to ensure the correctness and performance of the data.

Go: Byte Slice Manipulation with the Standard 'bytes' PackageGo: Byte Slice Manipulation with the Standard 'bytes' PackageMay 08, 2025 am 12:09 AM

The"bytes"packageinGooffersefficientfunctionsformanipulatingbyteslices.1)Usebytes.Joinforconcatenatingslices,2)bytes.Bufferforincrementalwriting,3)bytes.Indexorbytes.IndexByteforsearching,4)bytes.Readerforreadinginchunks,and5)bytes.SplitNor

Go encoding/binary package: Optimizing performance for binary operationsGo encoding/binary package: Optimizing performance for binary operationsMay 08, 2025 am 12:06 AM

Theencoding/binarypackageinGoiseffectiveforoptimizingbinaryoperationsduetoitssupportforendiannessandefficientdatahandling.Toenhanceperformance:1)Usebinary.NativeEndianfornativeendiannesstoavoidbyteswapping.2)BatchReadandWriteoperationstoreduceI/Oover

Go bytes package: short reference and tipsGo bytes package: short reference and tipsMay 08, 2025 am 12:05 AM

Go's bytes package is mainly used to efficiently process byte slices. 1) Using bytes.Buffer can efficiently perform string splicing to avoid unnecessary memory allocation. 2) The bytes.Equal function is used to quickly compare byte slices. 3) The bytes.Index, bytes.Split and bytes.ReplaceAll functions can be used to search and manipulate byte slices, but performance issues need to be paid attention to.

Go bytes package: practical examples for byte slice manipulationGo bytes package: practical examples for byte slice manipulationMay 08, 2025 am 12:01 AM

The byte package provides a variety of functions to efficiently process byte slices. 1) Use bytes.Contains to check the byte sequence. 2) Use bytes.Split to split byte slices. 3) Replace the byte sequence bytes.Replace. 4) Use bytes.Join to connect multiple byte slices. 5) Use bytes.Buffer to build data. 6) Combined bytes.Map for error processing and data verification.

Go Binary Encoding/Decoding: A Practical Guide with ExamplesGo Binary Encoding/Decoding: A Practical Guide with ExamplesMay 07, 2025 pm 05:37 PM

Go's encoding/binary package is a tool for processing binary data. 1) It supports small-endian and large-endian endian byte order and can be used in network protocols and file formats. 2) The encoding and decoding of complex structures can be handled through Read and Write functions. 3) Pay attention to the consistency of byte order and data type when using it, especially when data is transmitted between different systems. This package is suitable for efficient processing of binary data, but requires careful management of byte slices and lengths.

Go 'bytes' Package: Compare, Join, Split & MoreGo 'bytes' Package: Compare, Join, Split & MoreMay 07, 2025 pm 05:29 PM

The"bytes"packageinGoisessentialbecauseitoffersefficientoperationsonbyteslices,crucialforbinarydatahandling,textprocessing,andnetworkcommunications.Byteslicesaremutable,allowingforperformance-enhancingin-placemodifications,makingthispackage

Go Strings Package: Essential Functions You Need to KnowGo Strings Package: Essential Functions You Need to KnowMay 07, 2025 pm 04:57 PM

Go'sstringspackageincludesessentialfunctionslikeContains,TrimSpace,Split,andReplaceAll.1)Containsefficientlychecksforsubstrings.2)TrimSpaceremoveswhitespacetoensuredataintegrity.3)SplitparsesstructuredtextlikeCSV.4)ReplaceAlltransformstextaccordingto

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.