http

package
v2.4.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 30, 2025 License: Apache-2.0 Imports: 33 Imported by: 3

Documentation

Index

Constants

View Source
const NotImplementedMessage = "Not implemented yet"

Variables

View Source
var HealthSimple = Ping

HealthSimple is an alias for the existing Ping function for backward compatibility. Use this when you don't need detailed dependency health checks.

Returns:

  • HTTP 200 OK with "healthy" text response

Example usage:

f.Get("/health", commonsHttp.HealthSimple)

Functions

func Accepted

func Accepted(c *fiber.Ctx, s any) error

Accepted sends an HTTP 202 Accepted response with a custom body.

func AllowFullOptionsWithCORS

func AllowFullOptionsWithCORS(app *fiber.App)

AllowFullOptionsWithCORS set r.Use(WithCORS) and allow every request to use OPTION method.

func ApplyCursorPagination

func ApplyCursorPagination(
	findAll squirrel.SelectBuilder,
	decodedCursor Cursor,
	orderDirection string,
	limit int,
	tableAlias ...string,
) (squirrel.SelectBuilder, string)

func BadRequest

func BadRequest(c *fiber.Ctx, s any) error

BadRequest sends an HTTP 400 Bad Request response with a custom body.

func Conflict

func Conflict(c *fiber.Ctx, code, title, message string) error

Conflict sends an HTTP 409 Conflict response with a custom code, title and message.

func Created

func Created(c *fiber.Ctx, s any) error

Created sends an HTTP 201 Created response with a custom body.

func ExtractTokenFromHeader

func ExtractTokenFromHeader(c *fiber.Ctx) string

ExtractTokenFromHeader extracts the authentication token from the Authorization header. It handles both "Bearer TOKEN" format and raw token format.

func File

func File(filePath string) fiber.Handler

File servers a specific file.

func Forbidden

func Forbidden(c *fiber.Ctx, code, title, message string) error

Forbidden sends an HTTP 403 Forbidden response with a custom code, title and message.

func HandleFiberError

func HandleFiberError(c *fiber.Ctx, err error) error

HandleFiberError handles errors for Fiber, properly unwrapping errors to check for fiber.Error

func HealthWithDependencies added in v2.4.0

func HealthWithDependencies(dependencies ...DependencyCheck) fiber.Handler

HealthWithDependencies creates a Fiber handler that reports health status based on circuit breaker states and custom health checks.

Returns HTTP 200 (status: "available") when all dependencies are healthy, or HTTP 503 (status: "degraded") when any dependency fails.

Example:

f.Get("/health", commonsHttp.HealthWithDependencies(
    commonsHttp.DependencyCheck{
        Name:           "database",
        CircuitBreaker: cbManager,
        ServiceName:    "postgres",
        HealthCheck:    func() bool { return db.Ping() == nil },
    },
    commonsHttp.DependencyCheck{
        Name:           "cache",
        CircuitBreaker: cbManager,
        ServiceName:    "redis",
    },
))

func InternalServerError

func InternalServerError(c *fiber.Ctx, code, title, message string) error

InternalServerError sends an HTTP 500 Internal Server Response response

func JSONResponse

func JSONResponse(c *fiber.Ctx, status int, s any) error

JSONResponse sends a custom status code and body as a JSON response.

func JSONResponseError

func JSONResponseError(c *fiber.Ctx, err commons.Response) error

JSONResponseError sends a JSON formatted error response with a custom error struct.

func KeyByHeader added in v2.4.0

func KeyByHeader(headerName string) func(*fiber.Ctx) string

KeyByHeader generates rate limit key from a specific header. Useful for API keys, tenant IDs, or custom identifiers.

func KeyByIP added in v2.4.0

func KeyByIP(c *fiber.Ctx) string

KeyByIP generates rate limit key from client IP address. This is the most common strategy and protects against IP-based attacks.

func KeyByIPAndEndpoint added in v2.4.0

func KeyByIPAndEndpoint(c *fiber.Ctx) string

KeyByIPAndEndpoint generates rate limit key from IP and endpoint path. This allows different rate limits per endpoint while still tracking per-IP.

func KeyComposite added in v2.4.0

func KeyComposite(generators ...func(*fiber.Ctx) string) func(*fiber.Ctx) string

KeyComposite generates a composite key from multiple dimensions. This allows hierarchical rate limiting (e.g., limit per IP AND per user). Example usage:

KeyComposite(
  func(c) string { return "ip:" + c.IP() },
  func(c) string { return "endpoint:" + c.Path() },
)

func NoContent

func NoContent(c *fiber.Ctx) error

NoContent sends an HTTP 204 No Content response without anybody.

func NotFound

func NotFound(c *fiber.Ctx, code, title, message string) error

NotFound sends an HTTP 404 Not Found response with a custom code, title and message.

func NotImplemented

func NotImplemented(c *fiber.Ctx, message string) error

NotImplemented sends an HTTP 501 Not Implemented response with a custom message.

func NotImplementedEndpoint

func NotImplementedEndpoint(c *fiber.Ctx) error

NotImplementedEndpoint returns HTTP 501 with not implemented message.

func OK

func OK(c *fiber.Ctx, s any) error

OK sends an HTTP 200 OK response with a custom body.

func PaginateRecords

func PaginateRecords[T any](
	isFirstPage bool,
	hasPagination bool,
	pointsNext bool,
	items []T,
	limit int,
	orderUsed string,
) []T

func PartialContent

func PartialContent(c *fiber.Ctx, s any) error

PartialContent sends an HTTP 206 Partial Content response with a custom body.

func Ping

func Ping(c *fiber.Ctx) error

Ping returns HTTP Status 200 with response "pong".

func RangeNotSatisfiable

func RangeNotSatisfiable(c *fiber.Ctx) error

RangeNotSatisfiable sends an HTTP 416 Requested Range Not Satisfiable response.

func RateLimitMiddleware added in v2.4.0

func RateLimitMiddleware(config RateLimitConfig) fiber.Handler

RateLimitMiddleware creates a Fiber middleware for rate limiting. This middleware: 1. Extracts rate limit key from request (via KeyGenerator) 2. Checks rate limit using the Limiter 3. Sets standard rate limit response headers 4. Blocks request if rate limit exceeded 5. Handles errors gracefully based on FailureMode

This is a generic implementation suitable for any Fiber-based service.

func ServeReverseProxy

func ServeReverseProxy(target string, res http.ResponseWriter, req *http.Request)

ServeReverseProxy serves a reverse proxy for a given url.

func Unauthorized

func Unauthorized(c *fiber.Ctx, code, title, message string) error

Unauthorized sends an HTTP 401 Unauthorized response with a custom code, title and message.

func UnprocessableEntity

func UnprocessableEntity(c *fiber.Ctx, code, title, message string) error

UnprocessableEntity sends an HTTP 422 Unprocessable Entity response with a custom code, title and message.

func Version

func Version(c *fiber.Ctx) error

Version returns HTTP Status 200 with given version.

func Welcome

func Welcome(service string, description string) fiber.Handler

Welcome returns HTTP Status 200 with service info.

func WithBasicAuth

func WithBasicAuth(f BasicAuthFunc, realm string) fiber.Handler

WithBasicAuth creates a basic authentication middleware.

func WithCORS

func WithCORS() fiber.Handler

WithCORS is a middleware that enables CORS. Replace it with a real CORS middleware implementation.

func WithGrpcLogging

func WithGrpcLogging(opts ...LogMiddlewareOption) grpc.UnaryServerInterceptor

WithGrpcLogging is a gRPC unary interceptor to log access to gRPC server.

func WithHTTPLogging

func WithHTTPLogging(opts ...LogMiddlewareOption) fiber.Handler

WithHTTPLogging is a middleware to log access to http server. It logs access log according to Apache Standard Logs which uses Common Log Format (CLF) Ref: https://httpd.apache.org/docs/trunk/logs.html#common

Types

type BasicAuthFunc

type BasicAuthFunc func(username, password string) bool

BasicAuthFunc represents a func which returns if a username and password was authenticated or not. It returns true if authenticated, and false when not authenticated.

func FixedBasicAuthFunc

func FixedBasicAuthFunc(username, password string) BasicAuthFunc

FixedBasicAuthFunc is a fixed username and password to use as BasicAuthFunc.

type Cursor

type Cursor struct {
	ID         string `json:"id"`
	PointsNext bool   `json:"points_next"`
}

func CreateCursor

func CreateCursor(id string, pointsNext bool) Cursor

func DecodeCursor

func DecodeCursor(cursor string) (Cursor, error)

type CursorPagination

type CursorPagination struct {
	Next string `json:"next"`
	Prev string `json:"prev"`
}

func CalculateCursor

func CalculateCursor(
	isFirstPage, hasPagination, pointsNext bool,
	firstItemID, lastItemID string,
) (CursorPagination, error)

type DependencyCheck added in v2.4.0

type DependencyCheck struct {
	// Name is the identifier for this dependency in the health response
	Name string

	// CircuitBreaker is the circuit breaker manager (optional)
	// When provided with ServiceName, health endpoint will report circuit breaker state
	CircuitBreaker circuitbreaker.Manager

	// ServiceName is the name used to register this dependency with the circuit breaker
	// Required if CircuitBreaker is provided
	ServiceName string

	// HealthCheck is a custom health check function (optional)
	// When provided, this function will be called to determine dependency health
	// Return true for healthy, false for unhealthy
	HealthCheck func() bool
}

DependencyCheck represents a health check configuration for a single dependency.

At minimum, provide a Name. For circuit breaker integration, provide both CircuitBreaker and ServiceName. For custom health logic, provide HealthCheck.

type DependencyStatus added in v2.4.0

type DependencyStatus struct {
	// CircuitBreakerState indicates the current circuit breaker state (closed, open, half-open)
	// Only populated when circuit breaker is configured for this dependency
	CircuitBreakerState string `json:"circuit_breaker_state,omitempty"`

	// Healthy indicates whether the dependency is currently healthy
	Healthy bool `json:"healthy"`

	// Requests is the total number of requests processed by the circuit breaker
	// Only populated when circuit breaker is configured
	Requests uint32 `json:"requests,omitempty"`

	// TotalSuccesses is the cumulative count of successful requests
	// Only populated when circuit breaker is configured
	TotalSuccesses uint32 `json:"total_successes,omitempty"`

	// TotalFailures is the cumulative count of failed requests
	// Only populated when circuit breaker is configured
	TotalFailures uint32 `json:"total_failures,omitempty"`

	// ConsecutiveFailures is the count of consecutive failures
	// Resets to 0 on success. Only populated when circuit breaker is configured
	ConsecutiveFailures uint32 `json:"consecutive_failures,omitempty"`
}

DependencyStatus represents the health status of a single dependency. This struct provides type-safe representation of dependency health metrics.

type LogMiddlewareOption

type LogMiddlewareOption func(l *logMiddleware)

LogMiddlewareOption represents the log middleware function as an implementation.

func WithCustomLogger

func WithCustomLogger(logger log.Logger) LogMiddlewareOption

WithCustomLogger is a functional option for logMiddleware.

type RateLimitConfig added in v2.4.0

type RateLimitConfig struct {
	// Limiter is the rate limiting implementation (usually Redis-backed)
	Limiter ratelimit.Limiter

	// KeyGenerator extracts the rate limit key from the request
	// Examples:
	//   - By IP: func(c) string { return c.IP() }
	//   - By User: func(c) string { return extractUserID(c) }
	//   - By API Key: func(c) string { return c.Get("X-API-Key") }
	KeyGenerator func(c *fiber.Ctx) string

	// SkipPaths defines paths that bypass rate limiting
	// Typically: health checks, metrics endpoints
	SkipPaths []string

	// FailureMode determines behavior when rate limiter fails
	// FailOpen: Allow requests (prioritize availability)
	// FailClosed: Block requests (prioritize security)
	FailureMode ratelimit.FailureMode

	// ErrorCode is returned when rate limit is exceeded
	ErrorCode string

	// ErrorMessage is the human-readable error message
	ErrorMessage string

	// IncludeHeaders controls whether to add rate limit headers
	// Standard headers: X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset
	IncludeHeaders bool

	// Logger is an optional function for logging rate limit events
	// If nil, no logging is performed (service can inject its own logger)
	Logger func(level string, format string, args ...any)

	// OnRateLimitExceeded is an optional callback when rate limit is exceeded
	// Useful for metrics, alerts, or custom actions
	OnRateLimitExceeded func(c *fiber.Ctx, key string, result *ratelimit.Result)

	// OnError is an optional callback when rate limiter encounters errors
	// Useful for metrics, alerts, or custom error handling
	OnError func(c *fiber.Ctx, err error)
}

RateLimitConfig configures the rate limiting middleware for Fiber. This is a generic configuration that can be used across all Fiber-based services.

type RequestInfo

type RequestInfo struct {
	Method        string
	Username      string
	URI           string
	Referer       string
	RemoteAddress string
	Status        int
	Date          time.Time
	Duration      time.Duration
	UserAgent     string
	TraceID       string
	Protocol      string
	Size          int
	Body          string
}

RequestInfo is a struct design to store http access log data.

func NewRequestInfo

func NewRequestInfo(c *fiber.Ctx) *RequestInfo

NewRequestInfo creates an instance of RequestInfo.

func (*RequestInfo) CLFString

func (r *RequestInfo) CLFString() string

CLFString produces a log entry format similar to Common Log Format (CLF) Ref: https://httpd.apache.org/docs/trunk/logs.html#common

func (*RequestInfo) FinishRequestInfo

func (r *RequestInfo) FinishRequestInfo(rw *ResponseMetricsWrapper)

FinishRequestInfo calculates the duration of RequestInfo automatically using time.Now() It also set StatusCode and Size of RequestInfo passed by ResponseMetricsWrapper.

func (*RequestInfo) String

func (r *RequestInfo) String() string

String implements fmt.Stringer interface and produces a log entry using RequestInfo.CLFExtendedString.

type ResponseMetricsWrapper

type ResponseMetricsWrapper struct {
	Context    *fiber.Ctx
	StatusCode int
	Size       int
	Body       string
}

ResponseMetricsWrapper is a Wrapper responsible for collect the response data such as status code and size It implements built-in ResponseWriter interface.

type TelemetryMiddleware

type TelemetryMiddleware struct {
	Telemetry *opentelemetry.Telemetry
}

func NewTelemetryMiddleware

func NewTelemetryMiddleware(tl *opentelemetry.Telemetry) *TelemetryMiddleware

NewTelemetryMiddleware creates a new instance of TelemetryMiddleware.

func (*TelemetryMiddleware) EndTracingSpans

func (tm *TelemetryMiddleware) EndTracingSpans(c *fiber.Ctx) error

EndTracingSpans is a middleware that ends the tracing spans.

func (*TelemetryMiddleware) EndTracingSpansInterceptor

func (tm *TelemetryMiddleware) EndTracingSpansInterceptor() grpc.UnaryServerInterceptor

EndTracingSpansInterceptor is a gRPC interceptor that ends the tracing spans.

func (*TelemetryMiddleware) WithTelemetry

func (tm *TelemetryMiddleware) WithTelemetry(tl *opentelemetry.Telemetry, excludedRoutes ...string) fiber.Handler

WithTelemetry is a middleware that adds tracing to the context.

func (*TelemetryMiddleware) WithTelemetryInterceptor

func (tm *TelemetryMiddleware) WithTelemetryInterceptor(tl *opentelemetry.Telemetry) grpc.UnaryServerInterceptor

WithTelemetryInterceptor is a gRPC interceptor that adds tracing to the context.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL