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.

109 lines
2.8 KiB
Go

// Package httputil provides HTTP utility functions for the KnowFoolery application.
package httputil
import (
"github.com/gofiber/fiber/v3"
)
// Response represents a standard API response.
type Response struct {
Success bool `json:"success"`
Data interface{} `json:"data,omitempty"`
Meta *Meta `json:"meta,omitempty"`
}
// Meta contains response metadata.
type Meta struct {
Page int `json:"page,omitempty"`
PageSize int `json:"page_size,omitempty"`
TotalCount int64 `json:"total_count,omitempty"`
TotalPages int `json:"total_pages,omitempty"`
}
// NewResponse creates a new Response.
func NewResponse(data interface{}) Response {
return Response{
Success: true,
Data: data,
}
}
// NewPaginatedResponse creates a new paginated Response.
func NewPaginatedResponse(data interface{}, page, pageSize int, totalCount int64) Response {
totalPages := int(totalCount) / pageSize
if int(totalCount)%pageSize > 0 {
totalPages++
}
return Response{
Success: true,
Data: data,
Meta: &Meta{
Page: page,
PageSize: pageSize,
TotalCount: totalCount,
TotalPages: totalPages,
},
}
}
// OK sends a 200 OK response with data.
func OK(c fiber.Ctx, data interface{}) error {
return c.Status(fiber.StatusOK).JSON(NewResponse(data))
}
// Created sends a 201 Created response with data.
func Created(c fiber.Ctx, data interface{}) error {
return c.Status(fiber.StatusCreated).JSON(NewResponse(data))
}
// NoContent sends a 204 No Content response.
func NoContent(c fiber.Ctx) error {
return c.SendStatus(fiber.StatusNoContent)
}
// Paginated sends a paginated response.
func Paginated(c fiber.Ctx, data interface{}, page, pageSize int, totalCount int64) error {
return c.Status(fiber.StatusOK).JSON(NewPaginatedResponse(data, page, pageSize, totalCount))
}
// MessageResponse represents a simple message response.
type MessageResponse struct {
Success bool `json:"success"`
Message string `json:"message"`
}
// Message sends a simple message response.
func Message(c fiber.Ctx, message string) error {
return c.Status(fiber.StatusOK).JSON(MessageResponse{
Success: true,
Message: message,
})
}
// HealthResponse represents a health check response.
type HealthResponse struct {
Status string `json:"status"`
Service string `json:"service"`
Version string `json:"version"`
Checks map[string]string `json:"checks,omitempty"`
}
// Health sends a health check response.
func Health(c fiber.Ctx, service, version string, checks map[string]string) error {
status := "healthy"
for _, check := range checks {
if check != "ok" {
status = "unhealthy"
break
}
}
return c.Status(fiber.StatusOK).JSON(HealthResponse{
Status: status,
Service: service,
Version: version,
Checks: checks,
})
}