Skip to content

flew1x/go-lifeguard

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

go-lifeguard

go-lifeguard is a lightweight utility for managing background workers, HTTP/GRPC servers, health checks, and graceful shutdowns in Go applications.

Features

  • 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)

Installation

go get github.com/flew1x/go-lifeguard

Usage

Basic Example

import (
    "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()
}

Health Probe

probe := go_lifeguard.NewHealthProbe()
http.Handle("/healthz", probe.HealthHandler())

Graceful Shutdown

The library traps SIGINT and SIGTERM by default and waits for all workers and servers to finish or until the shutdown timeout is reached.

API Overview

  • 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()

Configuration

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)

License

MIT

About

A tiny, battle-tested library that gives every Go service the same rock-solid “platform primitives” in < 10 LOC

Topics

Resources

License

Stars

Watchers

Forks

Contributors

Languages