diff options
| author | Mel <einebeere@gmail.com> | 2024-12-29 17:21:06 +0100 |
|---|---|---|
| committer | Mel <einebeere@gmail.com> | 2024-12-29 17:21:06 +0100 |
| commit | 5025fab41ac37665ad35967f1f03c16588461605 (patch) | |
| tree | 526196063f63a88e5a7877bc136e7cb993d1bf82 /application/cmd | |
| parent | 54b021e352c6e8be605f4d223916ebf97a59f9a4 (diff) | |
| download | specimen-5025fab41ac37665ad35967f1f03c16588461605.tar.zst specimen-5025fab41ac37665ad35967f1f03c16588461605.zip | |
Simple Go HTTP server with graceful signal handling
Signed-off-by: Mel <einebeere@gmail.com>
Diffstat (limited to 'application/cmd')
| -rw-r--r-- | application/cmd/specimen/main.go | 58 |
1 files changed, 56 insertions, 2 deletions
diff --git a/application/cmd/specimen/main.go b/application/cmd/specimen/main.go index 8522b03..cf7ff36 100644 --- a/application/cmd/specimen/main.go +++ b/application/cmd/specimen/main.go @@ -1,10 +1,64 @@ package main import ( - "fmt" + "context" + "log/slog" + "os" + "os/signal" + "time" + "git.rnrd.eu/specimen/pkg/specimen" + "git.rnrd.eu/specimen/pkg/util" ) +const version = "3.3.3" + func main() { - fmt.Println(specimen.ASimpleMessage()) + ctx := context.Background() + logger := createLogger() + + if err := start(ctx, logger); err != nil { + logger.Error("failed to start the specimen application :(", util.SlogErr(err)) + os.Exit(1) + } +} + +func start(ctx context.Context, logger *slog.Logger) error { + // listen for SIGINT (or others on other systems, but who cares about those.. :3) + ctx, cancel := signal.NotifyContext(ctx, os.Interrupt) + defer cancel() + + logger.Info("starting the specimen application!", slog.String("version", version)) + + // start the specimen server! + server := specimen.NewServer(logger) + go server.Start(ctx) + + // listen for signals to gracefully shutdown the server + return listenForSignals(ctx, server, logger) +} + +func listenForSignals(ctx context.Context, server *specimen.Server, logger *slog.Logger) error { + // waiting for the global context to be done (happens on SIGINT) + <-ctx.Done() + logger.Info("received signal to shutdown the server, trying to gracefully shutdown...") + + shutdownCtx, cancelShutdown := context.WithTimeout(context.Background(), 5*time.Second) + defer cancelShutdown() + + if err := server.Shutdown(shutdownCtx); err != nil { + logger.Error("failed to gracefully shutdown the server :( forcing it.", util.SlogErr(err)) + os.Exit(1) + } + + logger.Info("specimen has been gracefully shutdown! goodbye!") + return nil +} + +func createLogger() *slog.Logger { + handlerOptions := slog.HandlerOptions{ + Level: slog.LevelDebug, + } + consoleHandler := slog.NewTextHandler(os.Stderr, &handlerOptions) + return slog.New(consoleHandler) } |
