Skip to content

Instantly share code, notes, and snippets.

@metalagman
Created June 3, 2025 15:11
Show Gist options
  • Save metalagman/9ce9fb71773cef0b5c32cdb7794c05af to your computer and use it in GitHub Desktop.
Save metalagman/9ce9fb71773cef0b5c32cdb7794c05af to your computer and use it in GitHub Desktop.
package fxrunner
import (
"context"
"fmt"
"os/signal"
"syscall"
"time"
"go.uber.org/fx"
)
// Run starts an fx application and handles graceful shutdown.
//
// It sets up a signal context to listen for SIGINT (Ctrl+C) and SIGTERM signals,
// which are used to trigger the shutdown of the application gracefully.
func Run(app *fx.App) error {
ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer cancel()
// Start the fx application using the provided context.
err := app.Start(ctx)
if err != nil {
return fmt.Errorf("start fx app: %w", err)
}
// Wait for the context to be done, which indicates that a shutdown signal was received.
<-ctx.Done()
// Stop the fx application gracefully using the background context with timeout.
shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 25*time.Second)
defer shutdownCancel()
err = app.Stop(shutdownCtx)
if err != nil {
return fmt.Errorf("stop fx app: %w", err)
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment