Documentation
¶
Overview ¶
Package http provides HTTP utilities and helpers for web applications. It includes cursor-based pagination, request handling, and response utilities.
Index ¶
- Constants
- func Accepted(c *fiber.Ctx, s any) error
- func AllowFullOptionsWithCORS(app *fiber.App)
- func ApplyCursorPagination(findAll squirrel.SelectBuilder, decodedCursor Cursor, orderDirection string, ...) (squirrel.SelectBuilder, string)
- func BadRequest(c *fiber.Ctx, s any) error
- func Conflict(c *fiber.Ctx, code, title, message string) error
- func Created(c *fiber.Ctx, s any) error
- func File(filePath string) fiber.Handler
- func Forbidden(c *fiber.Ctx, code, title, message string) error
- func InternalServerError(c *fiber.Ctx, code, title, message string) error
- func JSONResponse(c *fiber.Ctx, status int, s any) error
- func JSONResponseError(c *fiber.Ctx, err commons.Response) error
- func NewHTTPClientForProduction() (*http.Client, error)
- func NewHTTPClientWithOptions(opts ...ClientOption) (*http.Client, error)
- func NoContent(c *fiber.Ctx) error
- func NotFound(c *fiber.Ctx, code, title, message string) error
- func NotImplemented(c *fiber.Ctx, message string) error
- func NotImplementedEndpoint(c *fiber.Ctx) error
- func OK(c *fiber.Ctx, s any) error
- func PaginateRecords[T any](isFirstPage bool, hasPagination bool, pointsNext bool, items []T, limit int, ...) []T
- func PartialContent(c *fiber.Ctx, s any) error
- func Ping(c *fiber.Ctx) error
- func RangeNotSatisfiable(c *fiber.Ctx) error
- func ServeReverseProxy(target string, res http.ResponseWriter, req *http.Request)
- func Unauthorized(c *fiber.Ctx, code, title, message string) error
- func UnprocessableEntity(c *fiber.Ctx, code, title, message string) error
- func Version(c *fiber.Ctx) error
- func Welcome(service string, description string) fiber.Handler
- func WithBasicAuth(f BasicAuthFunc, realm string) fiber.Handler
- func WithCORS() fiber.Handler
- func WithGrpcLogging(opts ...LogMiddlewareOption) grpc.UnaryServerInterceptor
- func WithHTTPLogging(opts ...LogMiddlewareOption) fiber.Handler
- type BasicAuthFunc
- type ClientConfig
- type ClientOption
- func WithConnectionLimits(maxIdle, maxIdlePerHost, maxPerHost int) ClientOption
- func WithDefaultRetryJitter() ClientOption
- func WithHTTPFallback(allow bool) ClientOption
- func WithInternalNetworkMode() ClientOption
- func WithRetryConfig(enabled bool, maxRetries int, jitterConfig *retry.JitterConfig) ClientOption
- func WithTLSConfig(tlsConfig *tls.Config) ClientOption
- func WithTimeouts(timeout, dialTimeout, tlsTimeout time.Duration) ClientOption
- type Cursor
- type CursorPagination
- type HTTPClient
- type LogMiddlewareOption
- type RequestInfo
- type ResponseMetricsWrapper
- type TelemetryMiddleware
- func (tm *TelemetryMiddleware) EndTracingSpans(c *fiber.Ctx) error
- func (tm *TelemetryMiddleware) EndTracingSpansInterceptor() grpc.UnaryServerInterceptor
- func (tm *TelemetryMiddleware) WithTelemetry(tl *opentelemetry.Telemetry) fiber.Handler
- func (tm *TelemetryMiddleware) WithTelemetryInterceptor(tl *opentelemetry.Telemetry) grpc.UnaryServerInterceptor
Constants ¶
const NotImplementedMessage = "Not implemented yet"
NotImplementedMessage is the default message for not implemented endpoints.
Variables ¶
This section is empty.
Functions ¶
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) (squirrel.SelectBuilder, string)
ApplyCursorPagination applies cursor-based pagination to a query.
func BadRequest ¶
BadRequest sends an HTTP 400 Bad Request response with a custom body.
func Forbidden ¶
Forbidden sends an HTTP 403 Forbidden response with a custom code, title and message.
func InternalServerError ¶
InternalServerError sends an HTTP 500 Internal Server Response response
func JSONResponse ¶
JSONResponse sends a custom status code and body as a JSON response.
func JSONResponseError ¶
JSONResponseError sends a JSON formatted error response with a custom error struct.
func NewHTTPClientForProduction ¶ added in v1.12.1
NewHTTPClientForProduction creates a production-ready HTTP client
func NewHTTPClientWithOptions ¶ added in v1.12.1
func NewHTTPClientWithOptions(opts ...ClientOption) (*http.Client, error)
NewHTTPClientWithOptions creates an HTTP client with custom options
func NoContent ¶
func NoContent(c *fiber.Ctx) error
NoContent sends an HTTP 204 No Content response without anybody.
func NotFound ¶
NotFound sends an HTTP 404 Not Found response with a custom code, title and message.
func NotImplemented ¶
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 PaginateRecords ¶
func PaginateRecords[T any](isFirstPage bool, hasPagination bool, pointsNext bool, items []T, limit int, _ string) []T
PaginateRecords paginates records based on the cursor.
func PartialContent ¶
PartialContent sends an HTTP 206 Partial Content response with a custom body.
func RangeNotSatisfiable ¶
func RangeNotSatisfiable(c *fiber.Ctx) error
RangeNotSatisfiable sends an HTTP 416 Requested Range Not Satisfiable response.
func ServeReverseProxy ¶
func ServeReverseProxy(target string, res http.ResponseWriter, req *http.Request)
ServeReverseProxy serves a reverse proxy for a given url.
func Unauthorized ¶
Unauthorized sends an HTTP 401 Unauthorized response with a custom code, title and message.
func UnprocessableEntity ¶
UnprocessableEntity sends an HTTP 422 Unprocessable Entity response with a custom code, title and message.
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 ¶
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 ClientConfig ¶ added in v1.12.1
type ClientConfig struct {
// TLS Configuration
TLSConfig *tls.Config
// Connection timeouts
Timeout time.Duration
DialTimeout time.Duration
TLSHandshakeTimeout time.Duration
IdleConnTimeout time.Duration
// Connection limits
MaxIdleConns int
MaxIdleConnsPerHost int
MaxConnsPerHost int
// Security settings
InsecureSkipVerify bool // Only for development/testing - never use in production
MinTLSVersion uint16 // Minimum TLS version (default: TLS 1.2)
CipherSuites []uint16
AllowHTTPFallback bool // Allow fallback to HTTP if HTTPS fails (for internal networks)
PreferHTTPS bool // Try HTTPS first, fallback to HTTP if enabled
SSLVerificationStrict bool // Strict SSL verification (false for internal networks)
// Proxy settings
ProxyURL string
// Retry settings
EnableRetry bool // Enable automatic retries
MaxRetries int // Maximum number of retry attempts
RetryConfig *retry.JitterConfig // Retry configuration with jitter
}
ClientConfig holds configuration for creating HTTP clients
func DefaultClientConfig ¶ added in v1.12.1
func DefaultClientConfig() *ClientConfig
DefaultClientConfig returns a configuration with modern defaults
func InternalNetworkClientConfig ¶ added in v1.12.1
func InternalNetworkClientConfig() *ClientConfig
InternalNetworkClientConfig returns a configuration optimized for internal networks
func ProductionClientConfig ¶ added in v1.12.1
func ProductionClientConfig() *ClientConfig
ProductionClientConfig returns an extra-secure configuration for production use
type ClientOption ¶ added in v1.12.1
type ClientOption func(*ClientConfig) error
ClientOption allows customization of HTTP clients
func WithConnectionLimits ¶ added in v1.12.1
func WithConnectionLimits(maxIdle, maxIdlePerHost, maxPerHost int) ClientOption
WithConnectionLimits sets custom connection limits
func WithDefaultRetryJitter ¶ added in v1.12.1
func WithDefaultRetryJitter() ClientOption
WithDefaultRetryJitter enables retry with sensible defaults
func WithHTTPFallback ¶ added in v1.12.1
func WithHTTPFallback(allow bool) ClientOption
WithHTTPFallback enables/disables HTTP fallback for internal networks
func WithInternalNetworkMode ¶ added in v1.12.1
func WithInternalNetworkMode() ClientOption
WithInternalNetworkMode configures the client for internal network use
func WithRetryConfig ¶ added in v1.12.1
func WithRetryConfig(enabled bool, maxRetries int, jitterConfig *retry.JitterConfig) ClientOption
WithRetryConfig configures retry behavior with jitter
func WithTLSConfig ¶ added in v1.12.1
func WithTLSConfig(tlsConfig *tls.Config) ClientOption
WithTLSConfig sets a custom TLS configuration
func WithTimeouts ¶ added in v1.12.1
func WithTimeouts(timeout, dialTimeout, tlsTimeout time.Duration) ClientOption
WithTimeouts sets custom timeout values
type Cursor ¶
Cursor represents a cursor for pagination, containing an ID and direction information.
func CreateCursor ¶
CreateCursor creates a cursor encode struct.
func DecodeCursor ¶
DecodeCursor decodes a cursor string.
type CursorPagination ¶
CursorPagination entity to store cursor pagination to return to client
func CalculateCursor ¶
func CalculateCursor(isFirstPage, hasPagination, pointsNext bool, firstItemID, lastItemID string) (CursorPagination, error)
CalculateCursor calculates the cursor pagination.
type HTTPClient ¶ added in v1.12.1
type HTTPClient struct {
// contains filtered or unexported fields
}
HTTPClient wraps an HTTP client with intelligent protocol handling. The type name intentionally matches the package name for clarity in external usage.
func NewHTTPClient ¶ added in v1.12.1
func NewHTTPClient(config *ClientConfig) (*HTTPClient, error)
NewHTTPClient creates a client with smart protocol handling
func NewHTTPClientForInternalNetwork ¶ added in v1.12.1
func NewHTTPClientForInternalNetwork() (*HTTPClient, error)
NewHTTPClientForInternalNetwork creates an internal network-friendly HTTP client
func (*HTTPClient) Do ¶ added in v1.12.1
Do performs an HTTP request with intelligent protocol handling
func (*HTTPClient) DoWithRetry ¶ added in v1.12.1
DoWithRetry performs an HTTP request with retry logic and jitter
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 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 ¶
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
}
TelemetryMiddleware provides middleware for adding telemetry to HTTP handlers.
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) 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.