SoFunction
Updated on 2025-04-21

Detailed explanation of the example of Go language implementing elegant shutdown and restart

1. Elegant shutdown

Lifestyle examples

The restaurant closes: You went to the restaurant to eat hot pot, and just sat down and ordered the dishes (the client sent a request), the restaurant owner suddenly received a notice that the power was out (the shutdown order was received). The boss is very considerate. He first stops receiving new guests (stops receiving new requests), and waits for your table and other guests who are eating (the requests being processed) to finish eating before closing the door and leaving. In this way, your hot pot can be eaten safely and without any losses.

Code Example

package main
 
import (
	"context"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"
 
	"/gin-gonic/gin"
)
 
func main() {
	// Create a router	router := ()
	("/cook-hotpot", func(c *) {
		(5 * ) // It takes time to simulate hot pot cooking		(, "The hot pot is ready to eat!")
	})
 
	// Create a server	srv := &{
		Addr:    ":8080",
		Handler: router,
	}
 
	// Start the server in a separate goroutine	go func() {
		if err := (); err != nil && err !=  {
			("Server listening error: %s", err)
		}
	}()
 
	// Create a channel to receive system signals	quit := make(chan , 1)
	(quit, , ) // Listen to Ctrl+C and system termination signals 
	// Blocking waiting signal	<-quit
	("Start elegantly shut down...")
 
	// Set a 5-second timeout context	ctx, cancel := ((), 5*)
	defer cancel()
 
	// Call Shutdown method to elegantly close the server	if err := (ctx); err != nil {
		("Server elegant shutdown failed: %s", err)
	}
 
	("The server has been securely exited")
}

Verification effect

  • Run the above code and start the service.
  • Open the browser and visit http://127.0.0.1:8080/cook-hotpot, and start cooking hot pot by simulation.
  • Quickly execute the Ctrl+C command in the terminal and send a shutdown signal to the program.
  • The observation program will not exit immediately, but will wait until the hot pot is cooked (the request is processed) before exiting, achieving elegant shutdown.

2. Restart elegantly

Lifestyle examples

Security guard shift change: There are two security guards at the entrance of the community. Security guard A (old process) is on duty, and Security guard B (new process) is here to take over. Security A will not leave directly, but will wait until the matter at hand (such as dealing with a car entering) is done before letting security B take over the work. In this way, the order at the entrance of the community will not be affected by shift changes.

Code Example

package main
 
import (
	"log"
	"net/http"
	"time"
 
	"/fvbock/endless"
	"/gin-gonic/gin"
)
 
func main() {
	// Create a router	router := ()
	("/greet", func(c *) {
		(5 * ) // It takes time to simulate the request to process		(, "Hello, welcome to the community!")
	})
 
	// Use endless to start the server, support elegant restart	if err := (":8080", router); err != nil {
		("Server listening error: %s", err)
	}
 
	("The server has been securely exited")
}

Verification effect

  • Compile and run the above code, and the terminal will output the PID of the current process.
  • Modify the return value of the processing request function in the code, such as modifying "Hello, welcome to the community!" to "Welcome, the new security guard in the community is here!", and then recompile.
  • Open the browser and visit http://127.0.0.1:8080/greet to simulate the vehicle entering the community.
  • Quickly execute the kill -1 <PID> command in the terminal to send an elegant restart signal to the program.
  • When the current request is processed (Security A has processed the matter at hand), a new welcome message will be received when accessing again, indicating that the elegant restart has been completed without affecting the current request, and the process number has also become a new one (Security B takes over).

3. Summary

The core of elegant shutdown and elegant restart is "there is a beginning and an end", and you don't care about what you are doing without silence.

Elegant shutdown is like a restaurant owner waiting for you to finish the hot pot before closing the door. By monitoring the system signals (such as Ctrl+C), calling the Shutdown() method, stop receiving new requests and wait for the existing request to be processed.

Elegant restart is like a security guard changing shifts, using the endless library to listen for specific signals (such as SIGHUP), launching a new process to process new requests, and allowing the old process to process existing requests before exiting.

In actual projects, choose according to the needs: if you need to shut down the service safely, use elegant shutdown; if you need to update the code and do not affect the current network operation, use elegant restart.

This is the end of this article about the detailed explanation of the examples of Go to achieve elegant shutdown and restart. For more relevant content on elegant shutdown and restart of Go, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!