1
0
Fork 0
golang-github-gofiber-fiber/middleware/healthcheck/healthcheck.go
Daniel Baumann 6d002e9543
Adding upstream version 2.52.6.
Signed-off-by: Daniel Baumann <daniel@debian.org>
2025-05-17 06:50:16 +02:00

61 lines
1.5 KiB
Go

package healthcheck
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/utils"
)
// HealthChecker defines a function to check liveness or readiness of the application
type HealthChecker func(*fiber.Ctx) bool
// ProbeCheckerHandler defines a function that returns a ProbeChecker
type HealthCheckerHandler func(HealthChecker) fiber.Handler
func healthCheckerHandler(checker HealthChecker) fiber.Handler {
return func(c *fiber.Ctx) error {
if checker == nil {
return c.Next()
}
if checker(c) {
return c.SendStatus(fiber.StatusOK)
}
return c.SendStatus(fiber.StatusServiceUnavailable)
}
}
func New(config ...Config) fiber.Handler {
cfg := defaultConfig(config...)
isLiveHandler := healthCheckerHandler(cfg.LivenessProbe)
isReadyHandler := healthCheckerHandler(cfg.ReadinessProbe)
return func(c *fiber.Ctx) error {
// Don't execute middleware if Next returns true
if cfg.Next != nil && cfg.Next(c) {
return c.Next()
}
if c.Method() != fiber.MethodGet {
return c.Next()
}
prefixCount := len(utils.TrimRight(c.Route().Path, '/'))
if len(c.Path()) >= prefixCount {
checkPath := c.Path()[prefixCount:]
checkPathTrimmed := checkPath
if !c.App().Config().StrictRouting {
checkPathTrimmed = utils.TrimRight(checkPath, '/')
}
switch {
case checkPath == cfg.ReadinessEndpoint || checkPathTrimmed == cfg.ReadinessEndpoint:
return isReadyHandler(c)
case checkPath == cfg.LivenessEndpoint || checkPathTrimmed == cfg.LivenessEndpoint:
return isLiveHandler(c)
}
}
return c.Next()
}
}