How to shut down a web server gracefully in Golang
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.
- 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) }
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.
- 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) } }
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.
- 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) } }
In the sample code we create a http.Server
instance named srv
and use it in signal.Notify
The 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.
- 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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.

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

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. �...

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

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,...

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

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

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...
