1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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)
}
|