Table of Contents
1. Use signal.Notify to catch signals
2. Common signals to handle
3. Graceful shutdown best practices
4. Don't forget to restore default behavior if needed
Home Backend Development Golang How do you handle signals in a Go application?

How do you handle signals in a Go application?

Aug 11, 2025 pm 08:01 PM
go signal processing

The correct way to process signals in Go applications is to use the os/signal package to monitor the signal and perform elegant shutdown. 1. Use signal.Notify to send SIGINT, SIGTERM and other signals to the channel; 2. Run the main service in goroutine and block the waiting signal; 3. After receiving the signal, perform elegant shutdown with timeout through context.WithTimeout; 4. Clean up resources such as closing database connections and stopping background goroutine; 5. Use signal.Reset to restore the default signal behavior when necessary to ensure that the program can be reliably terminated in Kubernetes and other environments.

How do you handle signals in a Go application?

Handling signals in a Go application is essential for graceful shutdowns, cleanup, and responding to OS-level events like SIGTERM , SIGINT , or SIGHUP . Go provides a clean and simple way to work with signals through the os/signal package.

How do you handle signals in a Go application?

Here's how you typically handle signals in Go:

1. Use signal.Notify to catch signals

The main approach is to set up a signal listener using signal.Notify , which sends incoming signals to a channel. This is usually done in a separate goroutine so it doesn't block your main application.

How do you handle signals in a Go application?
 package main

import (
    "context"
    "fmt"
    "log"
    "net/http"
    "os"
    "os/signal"
    "syscall"
    "time"
)

func main() {
    // Create a server (example with HTTP)
    server := &http.Server{Addr: ":8080"}

    // Set up signal channel
    stop := make(chan os.Signal, 1)
    signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM)

    // Start server in a goroutine
    go func() {
        if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
            log.Fatalf("Server failed: %v", err)
        }
    }()

    fmt.Println("Server is running on :8080...")

    // Block until a signal is received
    <-stop
    fmt.Println("\nShutdown signal received.")

    // Gracefully shut down the server
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()

    if err := server.Shutdown(ctx); err != nil {
        log.Printf("Server shutdown error: %v", err)
    }

    fmt.Println("Server stopped gracefully.")
}

2. Common signals to handle

  • syscall.SIGINT — Triggered by Ctrl C (interrupt).
  • syscall.SIGTERM — Graceful termination signal (used by orchestration tools like Kubernetes).
  • syscall.SIGHUP — Often used to reload config (common in daemons).

You can include multiple signals in signal.Notify :

 signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP)

3. Graceful shutdown best practices

  • Avoid os.Exit() unless absolutely necessary — it skips cleanup.
  • Use context with timeout to limit how long shutdown can take.
  • Close resources: database connections, file handles, network listeners.
  • Stop background workers or goroutines using context cancellation.

Example of cleaning up background tasks:

How do you handle signals in a Go application?
 ctx, cancel := context.WithCancel(context.Background())

// Simulate a background task
go func() {
    ticker := time.NewTicker(2 * time.Second)
    for {
        select {
        case <-ticker.C:
            fmt.Println("Working...")
        case <-ctx.Done():
            fmt.Println("Worker stopped.")
            Return
        }
    }
}()

// Later, on signal:
<-stop
cancel() // stop the worker

4. Don't forget to restore default behavior if needed

If you're building a long-running daemon or need to temporarily stop listening for signals, you can use signal.Reset() :

 defer signal.Reset(syscall.SIGINT, syscall.SIGTERM)

This restores the default signal behavior after your program exits.


Handling signals properly ensures your Go apps behave predictably in production environments — especially under container orchestration. The pattern is simple: listen on a channel, block until a signal arrives, then clean up and exit gracefully.

Basically: set up a channel, notify it of signals, wait, then shut down. Not complicated — but easy to overlook.

The above is the detailed content of How do you handle signals in a Go application?. 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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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)

How do you work with environment variables in Golang? How do you work with environment variables in Golang? Aug 19, 2025 pm 02:06 PM

Goprovidesbuilt-insupportforhandlingenvironmentvariablesviatheospackage,enablingdeveloperstoread,set,andmanageenvironmentdatasecurelyandefficiently.Toreadavariable,useos.Getenv("KEY"),whichreturnsanemptystringifthekeyisnotset,orcombineos.Lo

How to implement a generic LRU cache in Go How to implement a generic LRU cache in Go Aug 18, 2025 am 08:31 AM

Use Go generics and container/list to achieve thread-safe LRU cache; 2. The core components include maps, bidirectional linked lists and mutex locks; 3. Get and Add operations ensure concurrency security through locks, with a time complexity of O(1); 4. When the cache is full, the longest unused entry will be automatically eliminated; 5. In the example, the cache with capacity of 3 successfully eliminated the longest unused "b". This implementation fully supports generic, efficient and scalable.

What is the reason for the rise of OKB coins? A detailed explanation of the strategic driving factors behind the surge in OKB coins What is the reason for the rise of OKB coins? A detailed explanation of the strategic driving factors behind the surge in OKB coins Aug 29, 2025 pm 03:33 PM

What is the OKB coin in the directory? What does it have to do with OKX transaction? OKB currency use supply driver: Strategic driver of token economics: XLayer upgrades OKB and BNB strategy comparison risk analysis summary In August 2025, OKX exchange's token OKB ushered in a historic rise. OKB reached a new peak in 2025, up more than 400% in just one week, breaking through $250. But this is not an accidental surge. It reflects the OKX team’s thoughtful shift in token model and long-term strategy. What is OKB coin? What does it have to do with OKX transaction? OKB is OK Blockchain Foundation and

Parsing RSS and Atom Feeds in a Go Application Parsing RSS and Atom Feeds in a Go Application Aug 18, 2025 am 02:40 AM

Use the gofeed library to easily parse RSS and Atomfeed. First, install the library through gogetgithub.com/mmcdole/gofeed, then create a Parser instance and call the ParseURL or ParseString method to parse remote or local feeds. The library will automatically recognize the format and return a unified feed structure. Then iterate over feed.Items to get standardized fields such as title, link, and publishing time. It is also recommended to set HTTP client timeouts, handle parsing errors, and use cache optimization performance to ultimately achieve simple, efficient and reliable feed resolution.

How to handle panics in a goroutine in Go How to handle panics in a goroutine in Go Aug 24, 2025 am 01:55 AM

Tohandlepanicsingoroutines,usedeferwithrecoverinsidethegoroutinetocatchandmanagethemlocally.2.Whenapanicisrecovered,logitmeaningfully—preferablywithastacktraceusingruntime/debug.PrintStack—fordebuggingandmonitoring.3.Onlyrecoverfrompanicswhenyoucanta

Performance Comparison: Java vs. Go for Backend Services Performance Comparison: Java vs. Go for Backend Services Aug 14, 2025 pm 03:32 PM

Gotypicallyoffersbetterruntimeperformancewithhigherthroughputandlowerlatency,especiallyforI/O-heavyservices,duetoitslightweightgoroutinesandefficientscheduler,whileJava,thoughslowertostart,canmatchGoinCPU-boundtasksafterJIToptimization.2.Gouseslessme

How do you define and call a function in Go? How do you define and call a function in Go? Aug 14, 2025 pm 06:22 PM

In Go, defining and calling functions use the func keyword and following fixed syntax, first clarify the answer: the function definition must include name, parameter type, return type and function body, and pass in corresponding parameters when calling; 1. Use funcfunctionName(params) returnType{} syntax when defining functions, such as funcadd(a,bint)int{return b}; 2. Support multiple return values, such as funcdivide(a,bfloat64)(float64,bool){}; 3. Calling functions directly uses the function name with brackets to pass parameters, such as result:=add(3,5); 4. Multiple return values can be received by variables or

How to use Go for building blockchain applications How to use Go for building blockchain applications Aug 17, 2025 am 03:04 AM

To start building blockchain applications using Go, you must first master the core concepts of blockchain, 1. Understand blocks, hashing, immutability, consensus mechanism, P2P network and digital signatures; 2. Install Go and initialize projects, and use Go modules to manage dependencies; 3. Build a simple blockchain to learn principles by defining the block structure, implementing SHA-256 hashing, creating blockchain slices, generating new blocks and verification logic; 4. Use mature frameworks and libraries such as CosmosSDK, TendermintCore, Go-Ethereum or Badger in actual development to avoid duplicate wheels; 5. Use Go's goroutine and net/http or gorilla/websocke in actual development; 5. Use Go's goroutine and net/http or gorilla/websocke

See all articles