github.com/wormhole-foundation/wormhole-explorer/common@v0.0.0-20240604151348-09585b5b97c5/health/controller.go (about)

     1  package health
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/gofiber/fiber/v2"
     7  	"go.uber.org/zap"
     8  )
     9  
    10  // Controller definition.
    11  type Controller struct {
    12  	checks []Check
    13  	logger *zap.Logger
    14  }
    15  
    16  // NewController creates a Controller instance.
    17  func NewController(checks []Check, logger *zap.Logger) *Controller {
    18  	return &Controller{checks: checks, logger: logger}
    19  }
    20  
    21  // HealthCheck handler for the endpoint /health.
    22  func (c *Controller) HealthCheck(ctx *fiber.Ctx) error {
    23  	return ctx.JSON(struct {
    24  		Status string `json:"status"`
    25  	}{Status: "OK"})
    26  }
    27  
    28  // ReadyCheck handler for the endpoint /ready.
    29  func (c *Controller) ReadyCheck(ctx *fiber.Ctx) error {
    30  	rctx := ctx.Context()
    31  	requestID := fmt.Sprintf("%v", rctx.Value("requestid"))
    32  	for _, check := range c.checks {
    33  		if err := check(rctx); err != nil {
    34  			c.logger.Error("Ready check failed", zap.Error(err), zap.String("requestID", requestID))
    35  			return ctx.Status(fiber.StatusInternalServerError).JSON(struct {
    36  				Ready string `json:"ready"`
    37  				Error string `json:"error"`
    38  			}{Ready: "NO", Error: err.Error()})
    39  		}
    40  	}
    41  	return ctx.Status(fiber.StatusOK).JSON(struct {
    42  		Ready string `json:"ready"`
    43  	}{Ready: "OK"})
    44  
    45  }