go-lifeguard is a lightweight utility for managing background workers, HTTP/GRPC servers, health checks, and graceful shutdowns in Go applications.
- Graceful shutdown for HTTP and GRPC servers
- Background worker management (start, stop, list)
- Health probe endpoints (readiness)
- Startup and shutdown hooks
- Signal trapping (SIGINT, SIGTERM)
- Pluggable logger (zap)
go get github.com/flew1x/go-lifeguardimport (
"github.com/flew1x/go-lifeguard"
"go.uber.org/zap"
"net/http"
)
func main() {
lg, _ := go_lifeguard.New(nil)
// Register HTTP server
lg.HTTPServer(":8080", http.DefaultServeMux)
// Register a background worker
lg.Worker("example-worker", func(ctx context.Context) error {
// Your background logic here
<-ctx.Done()
return nil
})
// Run the application (blocks forever)
lg.Run()
}probe := go_lifeguard.NewHealthProbe()
http.Handle("/healthz", probe.HealthHandler())The library traps SIGINT and SIGTERM by default and waits for all workers and servers to finish or until the shutdown timeout is reached.
New(cfg *Config) (*Lifeguard, context.Context)(*Lifeguard) HTTPServer(addr string, h http.Handler)(*Lifeguard) GRPCServer(addr string, srv interface)(*Lifeguard) Worker(name string, fn func(context.Context) error)(*Lifeguard) AddWorker(name string, fn func(context.Context) error) error(*Lifeguard) ListWorkers() []WorkerStatus(*Lifeguard) RegisterStartupHook(hook func(context.Context) error)(*Lifeguard) RegisterShutdownHook(hook func(context.Context) error)(*Lifeguard) Run()(*Lifeguard) Cleanup()
You can customize shutdown timeout, logger, and additional signals via the Config struct.
cfg := &go_lifeguard.Config{
ShutdownTimeout: 10 * time.Second,
Logger: zap.NewExample(),
}
lg, _ := go_lifeguard.New(cfg)MIT