Home >Backend Development >Golang >How to Perform Cleanup Actions When an HTTP Server Exits?

How to Perform Cleanup Actions When an HTTP Server Exits?

DDD
DDDOriginal
2024-12-19 06:52:14761browse

How to Perform Cleanup Actions When an HTTP Server Exits?

Executing Actions Upon Program Termination

In the context of an HTTP server started using http.Handle, the question arises as to how to perform specific operations at the end of the program's execution. This scenario also includes handling cases when the program is terminated via Ctrl-C.

For Linux systems, this task can be accomplished by leveraging the os.Signal package to capture and handle signals. The answer provided employs os.Interrupt to detect a Ctrl-C event and initiate the desired operations before exiting.

The provided code snippet demonstrates the implementation of this approach:

import (
    "log"
    "os"
    "os/signal"
)

func main() {
    // Create a channel to receive signals
    sigchan := make(chan os.Signal)

    // Register to receive interrupt signals
    signal.Notify(sigchan, os.Interrupt)

    // Start a goroutine to handle signals
    go func() {
        // Wait for an interrupt signal
        <-sigchan

        // Log the event
        log.Println("Program killed!")

        // Perform final actions and wait for write operations to complete

        // Exit cleanly
        os.Exit(0)
    }()

    // Start the main program tasks
}

With this implementation, the main() goroutine can proceed with the primary tasks of the program. Upon receiving the Ctrl-C interrupt, the signal goroutine will handle the cleanup operations gracefully and then terminate the program.

The above is the detailed content of How to Perform Cleanup Actions When an HTTP Server Exits?. 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