You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

50 lines
1.0 KiB
Go

package serviceboot
import (
"context"
"time"
"github.com/gofiber/fiber/v3"
)
// ReadyCheck defines a readiness probe function.
type ReadyCheck struct {
Name string
Required bool
Probe func(ctx context.Context) error
}
// RegisterReadiness registers a standard /ready endpoint with named checks.
func RegisterReadiness(app *fiber.App, timeout time.Duration, checks ...ReadyCheck) {
if timeout <= 0 {
timeout = 2 * time.Second
}
app.Get("/ready", func(c fiber.Ctx) error {
ctx, cancel := context.WithTimeout(c.Context(), timeout)
defer cancel()
statusMap := make(map[string]string, len(checks))
httpStatus := fiber.StatusOK
for _, check := range checks {
if check.Name == "" || check.Probe == nil {
continue
}
if err := check.Probe(ctx); err != nil {
statusMap[check.Name] = "down"
if check.Required {
httpStatus = fiber.StatusServiceUnavailable
}
continue
}
statusMap[check.Name] = "ok"
}
return c.Status(httpStatus).JSON(fiber.Map{
"status": "ready",
"checks": statusMap,
})
})
}