Service Guardian is a health check and service registration library for Go microservices. It integrates NATS as a service registry and provides standardized Liveness Probe and Dependency Health Check functionality.
- Service Registration: Distributed service registration and discovery based on NATS JetStream Key-Value Store.
- Health Check:
- Liveness Probe: Provides
/healthHTTP endpoint for Kubernetes or Load Balancer to check service liveness. - Dependency Check: Supports connection checks for multiple dependency services:
- NATS
- Redis
- MongoDB
- PostgreSQL
- Debug Mode: Supports
pprofperformance profiling (enabled via environment variableAPP_DEBUG=true).
- Liveness Probe: Provides
- Dependency Monitoring: Automatically monitors the registration status of dependent services and marks them as unhealthy when they go offline.
Install the latest version:
go get github.com/LZStock-OS/service-guardianOr install a specific version:
go get github.com/LZStock-OS/service-guardian@v0.1.0See CHANGELOG.md for version history and release notes.
Here's a complete example integrating NATS registration and dependency checks:
package main
import (
"log"
"os"
"os/signal"
"syscall"
"github.com/nats-io/nats.go"
"github.com/LZStock-OS/service-guardian/health"
livenessServer "github.com/LZStock-OS/service-guardian/liveness"
natsregistery "github.com/LZStock-OS/service-guardian/nats"
"github.com/LZStock-OS/service-guardian/registry"
)
func main() {
// 1. Connect to NATS
nc, err := nats.Connect(nats.DefaultURL)
if err != nil {
log.Fatalf("NATS connection failed: %v", err)
}
defer nc.Close()
// 2. Initialize service registry
reg, err := natsregistery.New(nc, ®istry.ServiceInstance{
ID: "instance-1",
ServiceName: "my-service",
})
if err != nil {
log.Fatalf("Failed to create registry: %v", err)
}
// 3. Create Liveness Monitor
// Configure external dependencies to monitor (databases, message queues, etc.)
monitor := livenessServer.New(reg,
&health.Dependencies{
NatsConn: nc,
RedisClient: nil, // If using Redis, provide client here
MongoClient: nil, // If using MongoDB, provide client here
PostgresClient: nil, // If using PostgreSQL, provide gorm.DB here
},
"8080", // Health Check Port
)
// 4. Add gRPC/other service dependencies (optional)
// Monitor whether other services are alive in the registry
monitor.AddGrpcDependency("user-service", "order-service")
// 5. Start monitoring and HTTP Server
go monitor.Start()
log.Println("Service Guardian started on :8080")
// Graceful shutdown
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
monitor.Stop()
}| Variable Name | Description | Default |
|---|---|---|
APP_DEBUG |
If set to true, enables /debug/pprof/* endpoints for performance profiling |
false |
Run tests:
go test ./...This project is licensed under the MIT License.