Sobes.tech
Junior — Middle

How can the program be terminated when a request to stop its operation occurs in the current context?

sobes.tech AI

Answer from AI

In Go, to properly terminate a program upon a shutdown request, it is common to use a context (context.Context) with cancellation. This allows passing a cancellation signal to goroutines and ending their work correctly.

Example:

package main

import (
    "context"
    "fmt"
    "os"
    "os/signal"
    "syscall"
    "time"
)

func main() {
    ctx, cancel := context.WithCancel(context.Background())

    // Listen for system signals to stop
    sigs := make(chan os.Signal, 1)
    signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)

    go func() {
        <-sigs
        fmt.Println("Received stop signal")
        cancel() // send cancellation signal to context
    }()

    // Run work that listens to the context
    work(ctx)
}

func work(ctx context.Context) {
    for {
        select {
        case <-ctx.Done():
            fmt.Println("Work ending")
            return
        default:
            fmt.Println("Working...")
            time.Sleep(1 * time.Second)
        }
    }
}

Thus, when the OS signal is received, the program correctly terminates all processes and exits.

How can the program be terminated when a request to… - sobes.tech