Documentation ¶
Overview ¶
This package allows you to gracefully shutdown your app.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Option ¶
type Option func(*Shutdown)
Option is the options type to configure Shutdown.
func WithGracePeriodDuration ¶
WithGracePeriodDuration sets the grace period for all shutdown hooks to finish running. If not used, the default grace period is 30s.
type Shutdown ¶
type Shutdown struct {
// contains filtered or unexported fields
}
Shutdown provides a way to listen for signals and handle shutdown of an application gracefully.
Example ¶
package main import ( "context" "errors" "fmt" "io" "log" "log/slog" "net/http" "syscall" "time" "github.com/induzo/gocom/shutdown" ) func main() { textHandler := slog.NewTextHandler(io.Discard, nil) logger := slog.New(textHandler) shutdownHandler := shutdown.New( logger, shutdown.WithHooks( []shutdown.Hook{ { Name: "do something", ShutdownFn: func(_ context.Context) error { return nil }, }, }, ), shutdown.WithGracePeriodDuration(time.Second)) var srv http.Server go func() { if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { log.Fatalf("http server listen and serve: %s", err) } }() shutdownHandler.Add("http server", func(ctx context.Context) error { if err := srv.Shutdown(ctx); err != nil { return fmt.Errorf("http server shutdown: %w", err) } return nil }) if err := shutdownHandler.Listen( context.Background(), syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT); err != nil { log.Fatalf("graceful shutdown failed: %s. forcing exit.", err) } }
Output:
Click to show internal directories.
Click to hide internal directories.