56 lines
1.0 KiB
Go
56 lines
1.0 KiB
Go
package app
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"os"
|
|
"os/signal"
|
|
"syscall"
|
|
)
|
|
|
|
type App struct {
|
|
}
|
|
|
|
func New() *App {
|
|
return &App{}
|
|
}
|
|
|
|
func (app *App) Run() error {
|
|
// Context pour gérer l'arrêt gracieux
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
defer cancel()
|
|
|
|
// Channel pour capturer les signaux d'arrêt (Ctrl+c, etc...)
|
|
sigChan := make(chan os.Signal, 1)
|
|
signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)
|
|
|
|
// Channel pour les erreurs
|
|
errChan := make(chan error, 1)
|
|
|
|
// Lancer les app ici
|
|
go app.runWorker(ctx, errChan)
|
|
|
|
fmt.Println("App started, press CTRL+C to stop...")
|
|
|
|
select {
|
|
case err := <-errChan:
|
|
return fmt.Errorf("error in the app: %w", err)
|
|
case sig := <-sigChan:
|
|
fmt.Printf("\nSIGTERM received: %v, stopping app...\n", sig)
|
|
cancel() // Annule le context pour arrêter les goroutines
|
|
return nil
|
|
}
|
|
}
|
|
|
|
func (app *App) runWorker(ctx context.Context, err_chan chan<- error) {
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
fmt.Println("Worker stopped")
|
|
return
|
|
default:
|
|
// Logique métier ...
|
|
}
|
|
}
|
|
}
|