middlewares

package
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Jun 28, 2025 License: MIT Imports: 27 Imported by: 0

Documentation

Overview

Package middlewares provides HTTP middleware for business metrics collection

Package middlewares provides middleware functions for the Echo framework

Index

Constants

This section is empty.

Variables

View Source
var DefaultAuthMetricsConfig = AuthMetricsConfig{
	Skipper:     func(echo.Context) bool { return false },
	ServiceName: "cservice-api",
}

DefaultAuthMetricsConfig provides default configuration

View Source
var DefaultHTTPInstrumentationConfig = HTTPInstrumentationConfig{
	Skipper:     func(echo.Context) bool { return false },
	ServiceName: "cservice-api",
}

DefaultHTTPInstrumentationConfig provides default configuration

View Source
var DefaultHTTPTracingConfig = HTTPTracingConfig{
	Skipper:     func(echo.Context) bool { return false },
	ServiceName: "cservice-api",
}

DefaultHTTPTracingConfig provides default configuration

View Source
var DefaultHasAuthorizationConfig = HasAuthorizationConfig{
	JWTContextKey:   "user",
	AdminLevelClaim: "adm",
}
View Source
var DefaultReCAPTCHAConfig = ReCAPTCHAConfig{
	Skipper:   defaultSkipper,
	SecretKey: config.ServiceReCAPTCHASecretKey.GetString(),
	MinScore:  config.ServiceReCAPTCHAMinScore.GetFloat64(),
	FieldName: config.ServiceReCAPTCHAFieldName.GetString(),
}

DefaultReCAPTCHAConfig is the default configuration for the reCAPTCHA middleware

Functions

func ApplyReCAPTCHA added in v0.0.11

func ApplyReCAPTCHA(paths ...string) func(echo.Context) bool

ApplyReCAPTCHA returns a skipper that applies reCAPTCHA verification only to specific paths

func AuthMetrics added in v0.4.0

func AuthMetrics(meter metric.Meter) echo.MiddlewareFunc

AuthMetrics returns a middleware that collects authentication metrics

func AuthMetricsWithConfig added in v0.4.0

func AuthMetricsWithConfig(config AuthMetricsConfig) echo.MiddlewareFunc

AuthMetricsWithConfig returns a middleware with custom configuration

func BusinessMetricsMiddleware added in v0.4.0

func BusinessMetricsMiddleware(config BusinessMetricsConfig) echo.MiddlewareFunc

BusinessMetricsMiddleware creates middleware for collecting business metrics

func CreateContextLogger added in v0.4.0

func CreateContextLogger(ctx context.Context, baseLogger *slog.Logger) *slog.Logger

CreateContextLogger creates a context-aware logger that can be used outside of Echo handlers

func CreateContextWithBaggage added in v0.4.0

func CreateContextWithBaggage(c echo.Context, baggageMap map[string]string) context.Context

CreateContextWithBaggage creates a context with baggage for cross-service communication

func CreateRootSpan added in v0.4.0

func CreateRootSpan(c echo.Context, operationName string) (context.Context, trace.Span)

CreateRootSpan creates a new root span for HTTP requests

func DebugWithContext added in v0.4.0

func DebugWithContext(c echo.Context, msg string, args ...any)

DebugWithContext logs a debug message with trace context from Echo context

func EnsureRootSpan added in v0.4.0

func EnsureRootSpan(c echo.Context, serviceName string) (context.Context, trace.Span)

EnsureRootSpan ensures there's a root span for the HTTP request, creating one if needed

func ErrorWithContext added in v0.4.0

func ErrorWithContext(c echo.Context, msg string, args ...any)

ErrorWithContext logs an error message with trace context from Echo context

func ExtractTraceContext added in v0.4.0

func ExtractTraceContext(ctx context.Context, headers map[string]string) context.Context

ExtractTraceContext extracts trace context from HTTP headers

func GetBaggageFromContext added in v0.4.0

func GetBaggageFromContext(c echo.Context) map[string]string

GetBaggageFromContext extracts baggage from the current context

func GetLoggerFromContext added in v0.4.0

func GetLoggerFromContext(c echo.Context) *slog.Logger

GetLoggerFromContext retrieves the trace-aware logger from Echo context

func GetSpanID added in v0.4.0

func GetSpanID(c echo.Context) string

GetSpanID returns the span ID from the Echo context

func GetTraceID added in v0.4.0

func GetTraceID(c echo.Context) string

GetTraceID returns the trace ID from the Echo context

func HTTPInstrumentation added in v0.4.0

func HTTPInstrumentation(meter metric.Meter) echo.MiddlewareFunc

HTTPInstrumentation returns a middleware that instruments HTTP requests with OpenTelemetry metrics

func HTTPInstrumentationWithConfig added in v0.4.0

func HTTPInstrumentationWithConfig(config HTTPInstrumentationConfig) echo.MiddlewareFunc

HTTPInstrumentationWithConfig returns a middleware with custom configuration

func HTTPTracing added in v0.4.0

func HTTPTracing(tracerProvider trace.TracerProvider) echo.MiddlewareFunc

HTTPTracing returns a middleware that instruments HTTP requests with OpenTelemetry tracing

func HTTPTracingEnhanced added in v0.4.0

func HTTPTracingEnhanced(tracerProvider trace.TracerProvider, serviceName string) echo.MiddlewareFunc

HTTPTracingEnhanced returns an enhanced tracing middleware that adds custom attributes and log correlation

func HTTPTracingWithConfig added in v0.4.0

func HTTPTracingWithConfig(config HTTPTracingConfig) echo.MiddlewareFunc

HTTPTracingWithConfig returns a middleware with custom configuration

func HasAuthorization added in v0.0.6

func HasAuthorization(level int32, scopes ...string) echo.MiddlewareFunc

func HasAuthorizationWithConfig added in v0.0.6

func HasAuthorizationWithConfig(config HasAuthorizationConfig, level int32, scopes ...string) echo.MiddlewareFunc

func InfoWithContext added in v0.4.0

func InfoWithContext(c echo.Context, msg string, args ...any)

InfoWithContext logs an info message with trace context from Echo context

func InjectTraceHeaders added in v0.4.0

func InjectTraceHeaders(ctx context.Context, headers map[string]string)

InjectTraceHeaders injects trace context into HTTP headers for outgoing requests

func LogCorrelation added in v0.4.0

func LogCorrelation() echo.MiddlewareFunc

LogCorrelation returns a middleware that automatically adds trace context to logs

func LogCorrelationWithConfig added in v0.4.0

func LogCorrelationWithConfig(config LogCorrelationConfig) echo.MiddlewareFunc

LogCorrelationWithConfig returns a middleware with custom configuration

func LogWithContext added in v0.4.0

func LogWithContext(c echo.Context, level slog.Level, msg string, args ...any)

LogWithContext logs a message using the trace-aware logger from context

func LogWithTraceContext added in v0.4.0

func LogWithTraceContext(ctx context.Context, logger *slog.Logger, level slog.Level, msg string, args ...any)

LogWithTraceContext logs a message with trace context from a Go context

func PropagateContext added in v0.4.0

func PropagateContext(from echo.Context, to echo.Context)

PropagateContext propagates trace context from one Echo context to another

func PropagateToOutgoingRequest added in v0.4.0

func PropagateToOutgoingRequest(c echo.Context, req *http.Request) *http.Request

PropagateToOutgoingRequest propagates trace context to an outgoing HTTP request

func RateLimit added in v0.4.0

func RateLimit(rateLimiter ratelimit.RateLimiter) echo.MiddlewareFunc

RateLimit returns a rate limiting middleware with default configuration

func RateLimitWithConfig added in v0.4.0

func RateLimitWithConfig(config RateLimitConfig) echo.MiddlewareFunc

RateLimitWithConfig returns a rate limiting middleware with custom configuration

func ReCAPTCHA added in v0.0.11

func ReCAPTCHA() echo.MiddlewareFunc

ReCAPTCHA returns a middleware that validates Google reCAPTCHA v3 tokens

func ReCAPTCHAWithConfig added in v0.0.11

func ReCAPTCHAWithConfig(cfg ReCAPTCHAConfig) echo.MiddlewareFunc

ReCAPTCHAWithConfig returns a middleware with config that validates Google reCAPTCHA v3 tokens

func SetupGlobalPropagator added in v0.4.0

func SetupGlobalPropagator()

SetupGlobalPropagator configures the global trace propagator

func SkipReCAPTCHA added in v0.0.11

func SkipReCAPTCHA(paths ...string) func(echo.Context) bool

SkipReCAPTCHA returns a skipper that skips reCAPTCHA verification for specific paths

func StartChildSpan added in v0.4.0

func StartChildSpan(c echo.Context, operationName string, opts ...trace.SpanStartOption) (context.Context, trace.Span)

StartChildSpan creates a child span from the current Echo context

func StartSpan added in v0.4.0

func StartSpan(ctx context.Context, name string, opts ...trace.SpanStartOption) (context.Context, trace.Span)

StartSpan creates a new child span from the current context

func StartSpanFromEcho added in v0.4.0

func StartSpanFromEcho(c echo.Context, name string, opts ...trace.SpanStartOption) (context.Context, trace.Span)

StartSpanFromEcho creates a new child span from the Echo context

func WarnWithContext added in v0.4.0

func WarnWithContext(c echo.Context, msg string, args ...any)

WarnWithContext logs a warning message with trace context from Echo context

func WithTraceContext added in v0.4.0

func WithTraceContext(c echo.Context) context.Context

WithTraceContext creates a new context with trace information from Echo context

Types

type AuthMetricsConfig added in v0.4.0

type AuthMetricsConfig struct {
	// Skipper defines a function to skip middleware
	Skipper func(echo.Context) bool
	// AuthMetrics is the authentication metrics collector
	AuthMetrics *metrics.AuthMetrics
	// ServiceName is used for metric labeling
	ServiceName string
}

AuthMetricsConfig holds configuration for authentication metrics middleware

type BusinessMetricsConfig added in v0.4.0

type BusinessMetricsConfig struct {
	BusinessMetrics *metrics.BusinessMetrics
	Skipper         func(echo.Context) bool
}

BusinessMetricsConfig holds configuration for business metrics middleware

type HTTPInstrumentationConfig added in v0.4.0

type HTTPInstrumentationConfig struct {
	// Skipper defines a function to skip middleware
	Skipper func(echo.Context) bool
	// Meter is the OpenTelemetry meter for creating instruments
	Meter metric.Meter
	// ServiceName is used for metric labeling
	ServiceName string
}

HTTPInstrumentationConfig holds configuration for HTTP instrumentation middleware

type HTTPInstruments added in v0.4.0

type HTTPInstruments struct {
	// contains filtered or unexported fields
}

HTTPInstruments holds all the metric instruments for HTTP requests

type HTTPTracingConfig added in v0.4.0

type HTTPTracingConfig struct {
	// Skipper defines a function to skip middleware
	Skipper func(echo.Context) bool
	// TracerProvider is the OpenTelemetry tracer provider
	TracerProvider trace.TracerProvider
	// ServiceName is used for span naming and attributes
	ServiceName string
	// Propagator is used for trace context propagation
	Propagator propagation.TextMapPropagator
}

HTTPTracingConfig holds configuration for HTTP tracing middleware

type HasAuthorizationConfig added in v0.0.6

type HasAuthorizationConfig struct {
	JWTContextKey   string
	AdminLevelClaim string
}

type LogCorrelationConfig added in v0.4.0

type LogCorrelationConfig struct {
	// Skipper defines a function to skip middleware
	Skipper func(echo.Context) bool
	// Logger is the base logger to enhance with trace context
	Logger *slog.Logger
	// IncludeRequestDetails adds request details to log context
	IncludeRequestDetails bool
}

LogCorrelationConfig holds configuration for log correlation middleware

type RateLimitConfig added in v0.4.0

type RateLimitConfig struct {
	// Skipper defines a function to skip middleware
	Skipper func(c echo.Context) bool

	// RateLimiter is the rate limiter implementation
	RateLimiter ratelimit.RateLimiter

	// RequestsPerMinute is the number of requests allowed per minute
	RequestsPerMinute int

	// WindowMinutes is the time window in minutes
	WindowMinutes int

	// KeyGenerator generates the rate limit key for a request
	KeyGenerator func(c echo.Context) string

	// ErrorHandler handles rate limit exceeded errors
	ErrorHandler func(c echo.Context, retryAfter time.Duration) error

	// Mode determines which endpoints to rate limit
	Mode RateLimitMode

	// EndpointPatterns is a list of endpoint patterns to rate limit (used with RateLimitModeEndpoints)
	EndpointPatterns []string
}

RateLimitConfig defines the configuration for rate limiting middleware

func DefaultRateLimitConfig added in v0.4.0

func DefaultRateLimitConfig() RateLimitConfig

DefaultRateLimitConfig returns the default rate limit configuration

type RateLimitMode added in v0.4.0

type RateLimitMode string

RateLimitMode defines the rate limiting mode

const (
	// RateLimitModeGlobal applies rate limiting to all endpoints
	RateLimitModeGlobal RateLimitMode = "global"
	// RateLimitModeEndpoints applies rate limiting only to specified endpoints
	RateLimitModeEndpoints RateLimitMode = "endpoints"
	// RateLimitModeChannels applies rate limiting only to channel registration endpoints (legacy)
	RateLimitModeChannels RateLimitMode = "channels"
)

type ReCAPTCHAConfig added in v0.0.11

type ReCAPTCHAConfig struct {
	// Skipper defines a function to skip middleware
	Skipper func(c echo.Context) bool

	// SecretKey is the Google reCAPTCHA v3 secret key
	SecretKey string

	// MinScore is the minimum score threshold (0.0 to 1.0)
	MinScore float64

	// FieldName is the field name in the JSON payload containing the reCAPTCHA token
	FieldName string
}

ReCAPTCHAConfig holds configuration for the reCAPTCHA middleware

type ReCAPTCHAResponse added in v0.0.11

type ReCAPTCHAResponse struct {
	Success     bool      `json:"success"`
	Score       float64   `json:"score"`
	Action      string    `json:"action"`
	ChallengeTS time.Time `json:"challenge_ts"`
	Hostname    string    `json:"hostname"`
	ErrorCodes  []string  `json:"error-codes,omitempty"`
}

ReCAPTCHAResponse represents the response from Google's reCAPTCHA API

type VerifyReCAPTCHAFunc added in v0.0.11

type VerifyReCAPTCHAFunc func(token, secretKey string) (*ReCAPTCHAResponse, error)

VerifyReCAPTCHAFunc defines the function signature for reCAPTCHA verification

Jump to

Keyboard shortcuts

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