feat: add root ctx cancel

main v0.0.10
git 2025-12-26 18:03:38 +08:00
parent 7d9d206e49
commit 81e1aea8c9
Signed by: git
GPG Key ID: 3F65EFFA44207ADD
1 changed files with 17 additions and 7 deletions

View File

@ -5,6 +5,7 @@ import (
"context" "context"
"errors" "errors"
"fmt" "fmt"
"log/slog"
"os" "os"
"os/signal" "os/signal"
"syscall" "syscall"
@ -15,10 +16,8 @@ import (
) )
var ( var (
// SignalChan ... // errSignal ...
SignalChan = make(chan os.Signal, 1) errSignal = errors.New("signal")
// ErrSignal ...
ErrSignal = errors.New("signal")
) )
// Run provides the common boilerplate code around executing a cobra command. // Run provides the common boilerplate code around executing a cobra command.
@ -42,17 +41,28 @@ func Run(cmd *cobra.Command) int {
} }
func execute(cmd *cobra.Command) error { func execute(cmd *cobra.Command) error {
ctx := context.Background() ctx, cancel := context.WithCancelCause(context.Background())
// graceful shutdown signal // graceful shutdown signal
signal.Notify(SignalChan, syscall.SIGINT, syscall.SIGTERM) signalChan := make(chan os.Signal, 1)
signal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM)
go func() {
select {
case s := <-signalChan:
slog.WarnContext(ctx, "Signal received", "signal", s)
cancel(fmt.Errorf("%w %s received", errSignal, s))
case <-ctx.Done():
}
}()
err := cmd.ExecuteContext(ctx) err := cmd.ExecuteContext(ctx)
if err == nil { if err == nil {
return nil return nil
} }
if errors.Is(err, ErrSignal) { if errors.Is(err, errSignal) {
return nil return nil
} }
return err return err
} }