summaryrefslogtreecommitdiffstats
path: root/runner/run.go
diff options
context:
space:
mode:
Diffstat (limited to 'runner/run.go')
-rw-r--r--runner/run.go58
1 files changed, 58 insertions, 0 deletions
diff --git a/runner/run.go b/runner/run.go
new file mode 100644
index 0000000..4527bea
--- /dev/null
+++ b/runner/run.go
@@ -0,0 +1,58 @@
+package runner
+
+import (
+ "context"
+ "flag"
+ "log/slog"
+ "os"
+ "os/signal"
+
+ "go.sudomsg.com/kit/logging"
+)
+
+// LoadWithArgs initializes context, signal handling, flag parsing, and runs the given application callback.
+//
+// - args: Command-line arguments (excluding/exact os.Args).
+// - run: Callback function (your main app logic). Receives a context (with signal cancellation),
+// a FlagSet (ready for use but not yet parsed), and trailing arguments.
+//
+// Handles panics and logs via logging.RecoverAndLog.
+// Logs and exits on non-nil errors from the run callback.
+func LoadWithArgs(args []string, run func(ctx context.Context, fs *flag.FlagSet, args []string) error) {
+ ctx := context.Background()
+
+ ctx, stop := signal.NotifyContext(ctx)
+ defer stop()
+
+ defer func() {
+ if err := recover(); err != nil {
+ logging.RecoverAndLog(ctx, "Panicked", err)
+ os.Exit(1)
+ }
+ }()
+
+ name := "app"
+ if len(args) > 0 && args[0] != "" {
+ name = args[0]
+ args = args[1:]
+ }
+
+ fs := flag.NewFlagSet(name, flag.ExitOnError)
+
+ if err := run(ctx, fs, args); err != nil {
+ slog.ErrorContext(ctx, "Program Terminated", "error", err)
+ os.Exit(1)
+ }
+}
+
+// LoadWithArgs initializes context, signal handling, flag parsing, and runs the given application callback.
+//
+// - args: Command-line arguments (excluding/exact os.Args).
+// - run: Callback function (your main app logic). Receives a context (with signal cancellation),
+// a FlagSet (ready for use but not yet parsed), and trailing arguments.
+//
+// Handles panics and logs via logging.RecoverAndLog.
+// Logs and exits on non-nil errors from the run callback.
+func Load(run func(ctx context.Context, fs *flag.FlagSet, args []string) error) {
+ LoadWithArgs(os.Args, run)
+}