Home Backend Development Golang How to shut down a web server gracefully in Golang

How to shut down a web server gracefully in Golang

Apr 06, 2023 am 08:59 AM

Golang (or Go) is a programming language that features concurrency, readability, and ease of use, making it an indispensable tool for today's web development. However, sometimes it is necessary to shut down the web server during development, such as when performing system maintenance or when there are insufficient server resources. This article will introduce how to shut down the web server gracefully in Golang.

  1. Create Web Server

First, we need to create a Web server. The http package in Golang provides basic tools for developing web services. Here is a simple example:

package main

import (
    "fmt"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello World!")
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}
Copy after login

The sample code creates a function named handler that will respond to requests from http and return " Hello World!". The main function uses the ListenAndServe method to start the web server on the local port 8080.

  1. Capture the shutdown signal

Before shutting down the web server, we need to capture the shutdown signal. By catching the signal, we can execute custom code when the shutdown event occurs.

In Golang, the os/signal package provides methods for capturing operating system signals. Here is an example:

package main

import (
    "fmt"
    "net/http"
    "os"
    "os/signal"
    "syscall"
)

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello World!")
}

func main() {
    http.HandleFunc("/", handler)
    httpServer := &http.Server{Addr: ":8080"} // 创建一个http.Server实例

    // 创建一个signal.Notify实例
    signalChan := make(chan os.Signal, 1)
    signal.Notify(signalChan,
        syscall.SIGINT,  // 中断信号
        syscall.SIGTERM, // 终止信号
    )

    go func() {
        sig := <-signalChan
        fmt.Println("接收到信号并正在关闭服务器:", sig)

        if err := httpServer.Close(); err != nil {
            fmt.Println("服务关闭失败:", err)
        }

        os.Exit(0)
    }()

    fmt.Println("Web服务器正在运行")
    err := httpServer.ListenAndServe()
    if err != nil {
        fmt.Println("Web服务器启动失败:", err)
    }
}
Copy after login

This example code creates an http.Server instance named httpServer and calls it in signal.Notify Interrupt and termination signals are captured in the method. When the signal is received, we will close httpServer and call the os.Exit(0) method to exit the process.

It is worth noting that in order to prevent blocking, we put the signal capturing code in an anonymous function and use the go keyword to run it asynchronously as a goroutine.

  1. Graceful shutdown

The above describes how to capture the shutdown signal and shut down the web server when a shutdown event occurs. But if there are still requests waiting for responses while the server is shut down, some data may be lost. This is why we need to shut down the server gracefully.

In Golang, the http.Server type provides a way to shut down the web server gracefully. The following is an example:

var srv http.Server

func main() {
    http.HandleFunc("/", handler)

    go func() {
        sigChannel := make(chan os.Signal, 1)
        signal.Notify(sigChannel, syscall.SIGTERM)
        <-sigChannel

        ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
        defer cancel()

        if err := srv.Shutdown(ctx); err != nil {
            log.Fatalf("shutdown: %v", err)
        }
    }()

    if err := srv.ListenAndServe(); err != http.ErrServerClosed {
        log.Fatalf("listen: %v", err)
    }
}
Copy after login

In the sample code we create a http.Server instance named srv and use it in signal.NotifyThe termination signal is captured in the method.

When the signal is received, we create a context with a timeout (5 seconds by default) using the context.WithTimeout method and srv.Shutdown Method to shut down the server. This method waits for all requests to be processed before shutting down the server.

  1. Summary

In this article, we introduced how to shut down a web server gracefully in Golang. We first created a simple web server, then used operating system signals to capture the shutdown event and called the Close method of type http.Server to shut down the server.

Finally, we learned how to shut down the server gracefully so that all requests can be processed before shutting down the server. This is very important for web applications running in production environments as it avoids issues such as data loss and long downtime.

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

Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the vulnerabilities of Debian OpenSSL What are the vulnerabilities of Debian OpenSSL Apr 02, 2025 am 07:30 AM

OpenSSL, as an open source library widely used in secure communications, provides encryption algorithms, keys and certificate management functions. However, there are some known security vulnerabilities in its historical version, some of which are extremely harmful. This article will focus on common vulnerabilities and response measures for OpenSSL in Debian systems. DebianOpenSSL known vulnerabilities: OpenSSL has experienced several serious vulnerabilities, such as: Heart Bleeding Vulnerability (CVE-2014-0160): This vulnerability affects OpenSSL 1.0.1 to 1.0.1f and 1.0.2 to 1.0.2 beta versions. An attacker can use this vulnerability to unauthorized read sensitive information on the server, including encryption keys, etc.

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

PostgreSQL monitoring method under Debian PostgreSQL monitoring method under Debian Apr 02, 2025 am 07:27 AM

This article introduces a variety of methods and tools to monitor PostgreSQL databases under the Debian system, helping you to fully grasp database performance monitoring. 1. Use PostgreSQL to build-in monitoring view PostgreSQL itself provides multiple views for monitoring database activities: pg_stat_activity: displays database activities in real time, including connections, queries, transactions and other information. pg_stat_replication: Monitors replication status, especially suitable for stream replication clusters. pg_stat_database: Provides database statistics, such as database size, transaction commit/rollback times and other key indicators. 2. Use log analysis tool pgBadg

Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Apr 02, 2025 am 09:12 AM

Backend learning path: The exploration journey from front-end to back-end As a back-end beginner who transforms from front-end development, you already have the foundation of nodejs,...

How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? Apr 02, 2025 pm 04:54 PM

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

In Go, why does printing strings with Println and string() functions have different effects? In Go, why does printing strings with Println and string() functions have different effects? Apr 02, 2025 pm 02:03 PM

The difference between string printing in Go language: The difference in the effect of using Println and string() functions is in Go...

How to specify the database associated with the model in Beego ORM? How to specify the database associated with the model in Beego ORM? Apr 02, 2025 pm 03:54 PM

Under the BeegoORM framework, how to specify the database associated with the model? Many Beego projects require multiple databases to be operated simultaneously. When using Beego...

See all articles