Sobes.tech
Middle — Middle+

Каким образом реализуешь мягкую остановку службы или приложения для сохранения текущего состояния и завершения работы без потери данных?

sobes.tech AI

Answer from AI

To implement a graceful shutdown of a service or application in Go, it is common to handle OS signals (such as SIGINT, SIGTERM) and use a cancellable context (context.Context). This allows for proper termination of ongoing operations, saving state, and freeing resources.

Example:

package main

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

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

    // Handle signals for graceful shutdown
    sigs := make(chan os.Signal, 1)
    signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)

    go func() {
        <-sigs
        fmt.Println("Shutdown signal received, starting shutdown...")
        cancel() // Cancel the context
    }()

    // Run main logic with cancellation support
    run(ctx)
}

func run(ctx context.Context) {
    for {
        select {
        case <-ctx.Done():
            // Save state, release resources
            fmt.Println("Saving state and shutting down")
            time.Sleep(2 * time.Second) // simulate saving
            return
        default:
            // Main work
            fmt.Println("Working...")
            time.Sleep(1 * time.Second)
        }
    }
}

This approach allows for a proper shutdown without data loss or forceful interruption.