middleware

package
v1.21.21 Latest Latest
Warning

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

Go to latest
Published: Jun 14, 2026 License: Apache-2.0 Imports: 30 Imported by: 0

Documentation

Overview

Package middleware provides a comprehensive, configurable middleware system for Echo v4.

This package offers 20+ middleware types with YAML/JSON configuration support, CEL-based dynamic processing, and multiple preset configurations for different deployment scenarios (development, production, security-focused, etc.).

The middleware system emphasizes configuration-as-code through YAML files, making it easy to manage complex middleware setups across different environments.

Quick Start

The simplest way to get started is using one of the preset configurations:

e := echo.New()
middleware.ApplyDefaultMiddleware(e) // CORS, Logger, Recover, RequestID, Gzip, Secure

Or load configuration from a YAML file:

config, err := middleware.LoadConfigFromYAML("middleware.yaml")
if err != nil {
	log.Fatal(err)
}
middleware.ApplyMiddleware(e, config)

Configuration System

The middleware system supports multiple configuration approaches:

1. Preset configurations for common scenarios 2. YAML/JSON file-based configuration (recommended) 3. Programmatic configuration with Go structs 4. Dynamic configuration with CEL expressions

YAML Configuration Examples

Minimal Configuration

Load from examples/middleware/minimal.yaml:

# Minimal setup with just essentials
recover:
  stack_size: 4096
request_id:
  target_header: "X-Request-ID"

Development Configuration

Load from examples/middleware/development.yaml:

# Developer-friendly with permissive CORS
cors:
  allow_origins: ["*"]
  allow_methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"]
  allow_headers: ["*"]

logger:
  format: "[${time_rfc3339_nano}] ${method} ${uri} (${status}) ${latency_human}\n"

recover:
  stack_size: 8192  # Larger stack for debugging

Production Configuration

Load from examples/middleware/production.yaml:

# Security hardened for production
cors:
  allow_origins: ["https://yourdomain.com"]
  allow_credentials: true

logger:
  format: '{"time":"${time_rfc3339}","method":"${method}","uri":"${uri}","status":${status}}'

csrf:
  token_length: 32
  cookie_secure: true
  cookie_http_only: true

rate_limiter:
  requests_per_second: 20
  burst: 30

secure:
  hsts_max_age: 31536000
  content_security_policy: "default-src 'self'"

Loading YAML Configuration

config, err := middleware.LoadConfigFromYAML("middleware.yaml")
if err != nil {
	log.Fatalf("Failed to load middleware config: %v", err)
}

// Validate configuration
if err := middleware.ValidateConfig(config); err != nil {
	log.Fatalf("Invalid configuration: %v", err)
}

// Apply to Echo instance
middleware.ApplyMiddleware(e, config)

Middleware Categories

Core Middleware

Essential middleware for most applications:

cors:           # Cross-Origin Resource Sharing
logger:         # Request logging with customizable formats
recover:        # Panic recovery with stack traces
request_id:     # Unique request identifier generation

Security Middleware

Authentication and security hardening:

basic_auth:     # HTTP Basic Authentication with htpasswd/userpass files
jwt_auth:       # JWT authentication (HMAC/RSA/ECDSA) with CEL validation
key_auth:       # API key authentication
csrf:           # Cross-Site Request Forgery protection
secure:         # Security headers (XSS, HSTS, CSP, etc.)

Request/Response Processing

Content handling and transformation:

body_dump:      # Request/response body logging
body_limit:     # Request body size limiting
gzip:           # Response compression
decompress:     # Request decompression
interceptors:   # Generic CEL-based request/response processing

Performance and Reliability

Rate limiting and timeouts:

rate_limiter:   # Request rate limiting with memory store
timeout:        # Request timeout middleware
context_timeout: # Context-based timeout with custom handlers

Authentication Examples

Basic Authentication with htpasswd

From examples/middleware/authentication.yaml:

basic_auth:
  htpasswd_file: ".htpasswd"
  realm: "Admin Panel"

JWT Authentication

From examples/middleware/authentication.yaml:

jwt_auth:
  signing_key: "your-secret-key"
  signing_method: "HS256"
  token_lookup: "header:Authorization"
  token_prefix: "Bearer "
  validation: 'claims.exp > now() && claims.aud == "api"'

API Key Authentication

key_auth:
  key_lookup: "header:X-API-Key"

CEL Integration

The middleware system includes powerful CEL (Common Expression Language) integration for dynamic request/response processing through interceptors.

CEL Interceptors Example

From examples/middleware/cel-interceptors.yaml:

interceptors:
  # Authentication guard
  - name: "auth_guard"
    regex: "^/api/.*"
    condition: 'request.method != "OPTIONS"'
    request:
      - 'headers.get("Authorization") == "" ? {status: 401, body: "Unauthorized"} : null'

  # Response headers
  - name: "security_headers"
    regex: ".*"
    response:
      - '{headers: {"X-Content-Type-Options": "nosniff"}}'

Available CEL Functions

Request/response manipulation: setHeader(), returnStatus(), returnJSON()

Authentication helpers: hasRole(), getUser(), validateJWT()

Utility functions: jsonToXML() plus all Gomplate functions

Variables: request, response, context, headers, body, user, claims

Configuration Validation

All configurations are validated before application:

if err := middleware.ValidateConfig(config); err != nil {
	log.Fatalf("Invalid configuration: %v", err)
}

Validation checks include: - CORS credential/origin compatibility - Rate limiter positive values - Timeout positive durations - Body limit format validation - JWT key file existence - Proxy target URL validity

Error Handling

The middleware system provides: - Comprehensive configuration validation with detailed error messages - Graceful fallbacks for optional middleware - Structured error responses with proper HTTP status codes - Debug information in development, secure handling in production

Example Files

Complete YAML configuration examples are available in examples/middleware/:

- minimal.yaml - Essential middleware only - development.yaml - Developer-friendly settings - production.yaml - Production security hardening - security.yaml - Security-focused subset - authentication.yaml - All authentication methods - cel-interceptors.yaml - Advanced CEL examples - comprehensive.yaml - All middleware types demo

Programmatic Usage

While YAML configuration is recommended, programmatic configuration is also supported:

config := middleware.MiddlewareConfig{
	CORS: &middleware.CORSConfig{
		AllowOrigins:     []string{"https://example.com"},
		AllowCredentials: true,
	},
	RateLimiter: &middleware.RateLimiterConfig{
		RequestsPerSecond: 10,
		Burst:             15,
	},
}
middleware.ApplyMiddleware(e, config)

Testing

The package includes comprehensive test coverage and utilities:

func TestMyMiddleware(t *testing.T) {
	e := echo.New()
	config, _ := middleware.LoadConfigFromYAML("test-config.yaml")
	middleware.ApplyMiddleware(e, config)

	req := httptest.NewRequest(http.MethodGet, "/test", nil)
	rec := httptest.NewRecorder()

	e.ServeHTTP(rec, req)

	assert.Equal(t, http.StatusNotFound, rec.Code)
	assert.NotEmpty(t, rec.Header().Get("X-Request-Id"))
}

Best Practices

Security

  • Always use HTTPS in production with HTTPSRedirect
  • Enable CSRF protection for web applications
  • Set restrictive CORS origins (avoid "*" in production)
  • Use strong JWT signing keys and rotate them regularly
  • Implement rate limiting to prevent abuse

Performance

  • Enable compression with Gzip for API responses
  • Set appropriate timeouts to prevent resource exhaustion
  • Configure appropriate body limits based on use case
  • Use request IDs for tracing and debugging

Configuration Management

  • Use YAML files for environment-specific configs
  • Validate configurations before deployment
  • Use environment variables for secrets
  • Version your middleware configurations
  • Test configurations with unit tests

For detailed API reference and additional examples, see the complete configuration options in the source code and example files.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ApplyCompressionMiddleware

func ApplyCompressionMiddleware(e *echo.Echo)

ApplyCompressionMiddleware applies compression-focused middleware configuration to an Echo instance

func ApplyDefaultMiddleware

func ApplyDefaultMiddleware(e *echo.Echo)

ApplyDefaultMiddleware applies default middleware configuration to an Echo instance

func ApplyDevelopmentMiddleware

func ApplyDevelopmentMiddleware(e *echo.Echo)

ApplyDevelopmentMiddleware applies development-friendly middleware configuration to an Echo instance

func ApplyMiddleware

func ApplyMiddleware(e *echo.Echo, config MiddlewareConfig)

ApplyMiddleware applies the configured middleware to an Echo instance

func ApplyMinimalMiddleware

func ApplyMinimalMiddleware(e *echo.Echo)

ApplyMinimalMiddleware applies minimal middleware configuration to an Echo instance

func ApplyProductionMiddleware

func ApplyProductionMiddleware(e *echo.Echo)

ApplyProductionMiddleware applies production-ready middleware configuration to an Echo instance

func ApplyProxyGatewayMiddleware

func ApplyProxyGatewayMiddleware(e *echo.Echo)

ApplyProxyGatewayMiddleware applies proxy/gateway middleware configuration to an Echo instance

func ApplySecurityMiddleware

func ApplySecurityMiddleware(e *echo.Echo)

ApplySecurityMiddleware applies security-focused middleware configuration to an Echo instance

func CreateAuthVariables

func CreateAuthVariables(c echo.Context, user, password string) map[string]interface{}

CreateAuthVariables creates a variable map for authentication CEL expressions

func CreateJWTVariables

func CreateJWTVariables(c echo.Context, token *jwt.Token, claims jwt.MapClaims) map[string]interface{}

CreateJWTVariables creates a variable map for JWT CEL expressions

func CreateRequestVariables

func CreateRequestVariables(c echo.Context) map[string]interface{}

CreateRequestVariables creates a variable map for request processing CEL expressions

func CreateResponseVariables

func CreateResponseVariables(c echo.Context) map[string]interface{}

CreateResponseVariables creates a variable map for response processing CEL expressions

func EchoMiddleware

func EchoMiddleware(config MiddlewareConfig) []echo.MiddlewareFunc

EchoMiddleware configures and returns Echo middleware based on the provided configuration

func GetJWTClaims

func GetJWTClaims(c echo.Context) (jwt.MapClaims, bool)

GetJWTClaims is a helper function to extract JWT claims from Echo context

func GetJWTToken

func GetJWTToken(c echo.Context) (*jwt.Token, bool)

GetJWTToken is a helper function to extract JWT token from Echo context

func GetJWTUser

func GetJWTUser(c echo.Context) (string, bool)

GetJWTUser is a helper function to extract user from JWT claims

func InterceptorMiddleware

func InterceptorMiddleware(interceptors []*InterceptorConfig, celEngine *CELEngine) echo.MiddlewareFunc

InterceptorMiddleware creates generic request/response interceptor middleware

func JWTMiddleware

func JWTMiddleware(config *JWTAuthConfig, celEngine *CELEngine) echo.MiddlewareFunc

JWTMiddleware creates JWT authentication middleware based on configuration

func LogInterceptorActivity

func LogInterceptorActivity(c echo.Context, interceptorName string, phase string, result interface{})

LogInterceptorActivity logs interceptor activity for debugging

func SaveConfigToYAML

func SaveConfigToYAML(config MiddlewareConfig, filename string) error

SaveConfigToYAML saves middleware configuration to a YAML file. This function serializes a MiddlewareConfig struct to YAML format and writes it to the specified file with proper formatting.

Example usage:

config := middleware.DefaultConfig()
err := middleware.SaveConfigToYAML(config, "config/middleware.yaml")
if err != nil {
  log.Fatalf("Failed to save config: %v", err)
}

Parameters:

config - The middleware configuration to save
filename - Path where the YAML file should be written

Returns:

error - Any error that occurred during serialization or file writing

func ValidateConfig

func ValidateConfig(config MiddlewareConfig) error

ValidateConfig validates a middleware configuration for common issues. This function performs various validation checks to ensure the configuration is valid and can be safely used with Echo middleware.

Example usage:

if err := middleware.ValidateConfig(config); err != nil {
  log.Fatalf("Invalid config: %v", err)
}

Parameters:

config - The middleware configuration to validate

Returns:

error - Description of validation errors, or nil if valid

func ValidateInterceptorConfig

func ValidateInterceptorConfig(config *InterceptorConfig) error

ValidateInterceptorConfig validates interceptor configuration

func ValidateJWTConfig

func ValidateJWTConfig(config *JWTAuthConfig) error

ValidateJWTConfig validates JWT configuration

Types

type BasicAuthConfig

type BasicAuthConfig struct {
	// Validator is a function that validates username and password credentials.
	// Cannot be serialized to JSON/YAML, must be set programmatically.
	// Example: func(username, password string, c echo.Context) (bool, error) {
	//   return username == "admin" && password == "secret", nil
	// }
	Validator func(string, string, echo.Context) (bool, error) `json:"-" yaml:"-"`

	// HtpasswdFile path to Apache htpasswd file for user authentication.
	// Supports bcrypt, SHA1, and MD5 hashing algorithms.
	// Example: "auth/.htpasswd"
	HtpasswdFile string `json:"htpasswd_file,omitempty" yaml:"htpasswd_file,omitempty"`

	// UserpassFile path to simple user=password text file (one per line).
	// Passwords are stored in plain text. Use only for development.
	// Example: "auth/users.txt" with content like: "admin=secret123\nuser=password\n"
	UserpassFile string `json:"userpass_file,omitempty" yaml:"userpass_file,omitempty"`

	// Validation CEL expression for additional user validation logic.
	// Available variables: user (string), password (string), context (echo.Context)
	// Examples: 'user.startsWith("admin")', 'user.matches("[a-z]+") && len(password) >= 8'
	Validation string `json:"validation,omitempty" yaml:"validation,omitempty"`

	// Realm sets the authentication realm displayed in the browser's login prompt.
	// Examples: "Restricted Area", "Admin Panel", "API Access"
	// Default: "Restricted"
	Realm string `json:"realm,omitempty" yaml:"realm,omitempty"`
}

BasicAuthConfig configures HTTP Basic Authentication middleware. BasicAuth middleware provides HTTP Basic Authentication using username/password credentials with support for htpasswd files, simple user=password files, and CEL-based validation. See: https://echo.labstack.com/docs/middleware/basic-auth

type BodyDumpConfig

type BodyDumpConfig struct {
	Handler func(echo.Context, []byte, []byte) `json:"-"` // Body dump handler function, not serializable
}

BodyDumpConfig configures BodyDump middleware

type BodyLimitConfig

type BodyLimitConfig struct {
	// Limit sets the maximum allowed size for request bodies.
	// Examples: "1M" (1 megabyte), "500K" (500 kilobytes), "2G" (2 gigabytes)
	// Supported units: B, K, M, G, T, P
	// Default: "32M"
	Limit string `json:"limit" yaml:"limit"`
}

BodyLimitConfig configures request body size limiting middleware. BodyLimit middleware limits the size of request bodies to prevent abuse. See: https://echo.labstack.com/docs/middleware/body-limit

type CELEngine

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

CELEngine provides CEL expression evaluation with custom functions for middleware processing

func NewCELEngine

func NewCELEngine() (*CELEngine, error)

NewCELEngine creates a new CEL engine with custom functions for middleware processing

func (*CELEngine) Evaluate

func (ce *CELEngine) Evaluate(expression string, variables map[string]interface{}) (interface{}, error)

Evaluate evaluates a CEL expression with provided variables and returns the result

func (*CELEngine) EvaluateCondition

func (ce *CELEngine) EvaluateCondition(expression string, variables map[string]interface{}) (bool, error)

EvaluateCondition evaluates a CEL expression with provided variables and returns a boolean result

func (*CELEngine) EvaluateFirstNonNull

func (ce *CELEngine) EvaluateFirstNonNull(expressions []string, variables map[string]interface{}) (interface{}, error)

EvaluateFirstNonNull evaluates an array of CEL expressions and returns the first non-null result

type CORSConfig

type CORSConfig struct {
	// AllowOrigins defines a list of allowed origin domains for cross-origin requests.
	// Examples: ["https://example.com", "https://api.example.com"]
	// Use ["*"] to allow all origins (not recommended for production with credentials)
	// Default: ["*"]
	AllowOrigins []string `json:"allow_origins,omitempty" yaml:"allow_origins,omitempty"`

	// AllowMethods specifies which HTTP methods are allowed in cross-origin requests.
	// Examples: ["GET", "POST", "PUT", "DELETE", "OPTIONS"]
	// Default: ["GET", "HEAD", "PUT", "PATCH", "POST", "DELETE"]
	AllowMethods []string `json:"allow_methods,omitempty" yaml:"allow_methods,omitempty"`

	// AllowHeaders specifies which request headers can be used during the actual request.
	// Examples: ["Content-Type", "Authorization", "X-Requested-With"]
	// Use ["*"] to allow all headers (requires specific origin, not wildcard)
	// Default: []
	AllowHeaders []string `json:"allow_headers,omitempty" yaml:"allow_headers,omitempty"`

	// AllowCredentials indicates whether the response can be exposed when credentials flag is true.
	// When true, AllowOrigins cannot contain "*" wildcard.
	// Examples: true (for authenticated requests), false (for public APIs)
	// Default: false
	AllowCredentials bool `json:"allow_credentials,omitempty" yaml:"allow_credentials,omitempty"`

	// ExposeHeaders indicates which headers are safe to expose to the API of a CORS API specification.
	// Examples: ["Content-Length", "X-Total-Count", "X-Request-ID"]
	// Default: []
	ExposeHeaders []string `json:"expose_headers,omitempty" yaml:"expose_headers,omitempty"`

	// MaxAge indicates how long (in seconds) the results of a preflight request can be cached.
	// Examples: 86400 (24 hours), 3600 (1 hour)
	// Default: 0 (no caching)
	MaxAge int `json:"max_age,omitempty" yaml:"max_age,omitempty"`
}

CORSConfig configures Cross-Origin Resource Sharing (CORS) middleware. CORS enables secure cross-domain data transfers by controlling access from browsers. See: https://echo.labstack.com/docs/middleware/cors

type CSRFConfig

type CSRFConfig struct {
	// TokenLength sets the length of the CSRF token in bytes.
	// Examples: 32 (32 bytes = 256 bits), 16 (16 bytes = 128 bits)
	// Default: 32
	TokenLength uint8 `json:"token_length,omitempty" yaml:"token_length,omitempty"`

	// TokenLookup specifies where to look for the CSRF token.
	// Examples: "header:X-CSRF-Token", "form:_token", "query:csrf"
	// Default: "header:X-CSRF-Token"
	TokenLookup string `json:"token_lookup,omitempty" yaml:"token_lookup,omitempty"`

	// ContextKey sets the key used to store the token in the request context.
	// Examples: "csrf", "_csrf_token"
	// Default: "csrf"
	ContextKey string `json:"context_key,omitempty" yaml:"context_key,omitempty"`

	// CookieName sets the name of the CSRF cookie.
	// Examples: "_csrf", "csrf-token"
	// Default: "_csrf"
	CookieName string `json:"cookie_name,omitempty" yaml:"cookie_name,omitempty"`

	// CookieDomain sets the domain attribute of the CSRF cookie.
	// Examples: ".example.com", "api.example.com"
	// Default: ""
	CookieDomain string `json:"cookie_domain,omitempty" yaml:"cookie_domain,omitempty"`

	// CookiePath sets the path attribute of the CSRF cookie.
	// Examples: "/", "/api"
	// Default: ""
	CookiePath string `json:"cookie_path,omitempty" yaml:"cookie_path,omitempty"`

	// CookieMaxAge sets the max-age attribute of the CSRF cookie (seconds).
	// Examples: 3600 (1 hour), 86400 (24 hours)
	// Default: 86400 (24 hours)
	CookieMaxAge int `json:"cookie_max_age,omitempty" yaml:"cookie_max_age,omitempty"`

	// CookieSecure sets the secure attribute of the CSRF cookie.
	// Examples: true (HTTPS only), false (HTTP and HTTPS)
	// Default: false
	CookieSecure bool `json:"cookie_secure,omitempty" yaml:"cookie_secure,omitempty"`

	// CookieHTTPOnly sets the HttpOnly attribute of the CSRF cookie.
	// Examples: true (no JavaScript access), false (JavaScript accessible)
	// Default: false
	CookieHTTPOnly bool `json:"cookie_http_only,omitempty" yaml:"cookie_http_only,omitempty"`
}

CSRFConfig configures Cross-Site Request Forgery protection middleware. CSRF middleware protects against Cross-Site Request Forgery attacks using tokens. See: https://echo.labstack.com/docs/middleware/csrf

type ContextTimeoutConfig

type ContextTimeoutConfig struct {
	Timeout                    time.Duration                   `json:"timeout"` // Request timeout
	ErrorHandler               func(error, echo.Context) error `json:"-"`       // Timeout error handler, not serializable
	OnTimeoutRouteErrorHandler func(error, echo.Context)       `json:"-"`       // Timeout route error handler, not serializable
}

ContextTimeoutConfig configures ContextTimeout middleware

type DecompressConfig

type DecompressConfig struct {
	GzipDecompressPool interface{} `json:"-"` // Pool for gzip decompression, not serializable
}

DecompressConfig configures Decompress middleware

type GzipConfig

type GzipConfig struct {
	// Level sets the compression level for gzip.
	// Examples: 1 (fastest), 6 (balanced), 9 (best compression), -1 (default)
	// Range: -1 (default), 0 (no compression), 1-9 (compression levels)
	// Default: -1 (default compression)
	Level int `json:"level,omitempty" yaml:"level,omitempty"`
}

GzipConfig configures response compression middleware. Gzip middleware compresses HTTP responses to reduce bandwidth usage. See: https://echo.labstack.com/docs/middleware/gzip

type InterceptorConfig

type InterceptorConfig struct {
	// Name is a descriptive name for the interceptor (used in logs and debugging).
	// Examples: "api_auth", "admin_guard", "response_transformer"
	Name string `json:"name,omitempty" yaml:"name,omitempty"`

	// Regex pattern to match request paths for selective application.
	// Uses Go regexp syntax for flexible path matching.
	// Examples: "^/api/.*", "^/admin/.*", ".*\\.(jpg|png|gif)$"
	Regex string `json:"regex,omitempty" yaml:"regex,omitempty"`

	// Condition optional CEL expression for additional conditional logic.
	// Available variables: request (echo.Request), response (echo.Response), context (echo.Context)
	// Examples: 'request.method != "OPTIONS"', 'request.header.get("X-API-Key") != ""'
	// If empty, interceptor always applies to matching paths
	Condition string `json:"condition,omitempty" yaml:"condition,omitempty"`

	// Request array of CEL expressions for request processing.
	// First non-null return value is used for early response or request modification.
	// Available variables: request, context, headers (map), body (string)
	// Return format: {status: 401, headers: {...}, body: "..."}
	// Examples:
	//   - 'headers.get("Authorization") == "" ? {status: 401, body: "Unauthorized"} : null'
	//   - '{headers: {"X-Processed": "true"}}'
	Request []string `json:"request,omitempty" yaml:"request,omitempty"`

	// Response array of CEL expressions for response processing.
	// First non-null return value is used for response transformation.
	// Available variables: request, response, context, headers (map), body (string)
	// Return format: {headers: {...}, body: "...", status: 200}
	// Examples:
	//   - 'headers.get("Content-Type").contains("json") ? {headers: {"Cache-Control": "no-cache"}} : null'
	//   - 'response.status >= 400 ? null : {headers: {"X-Success": "true"}}'
	Response []string `json:"response,omitempty" yaml:"response,omitempty"`
}

InterceptorConfig configures generic request/response interceptors with CEL-based processing. Interceptors provide flexible middleware capabilities using CEL expressions for conditional logic and request/response transformation.

type InterceptorResult

type InterceptorResult struct {
	Status  int                    `json:"status,omitempty"`
	Headers map[string]string      `json:"headers,omitempty"`
	Body    string                 `json:"body,omitempty"`
	HTML    string                 `json:"html,omitempty"`
	JSON    map[string]interface{} `json:"json,omitempty"`
}

InterceptorResult represents the result of a CEL expression evaluation

type JWTAuthConfig

type JWTAuthConfig struct {
	// SigningKey is the secret key used to validate JWT tokens (for HMAC algorithms).
	// For RSA/ECDSA algorithms, use SigningKeyFile instead.
	// Examples: "my-secret-key", "${JWT_SECRET}"
	SigningKey string `json:"signing_key,omitempty" yaml:"signing_key,omitempty"`

	// SigningKeyFile path to file containing signing key (for RSA/ECDSA algorithms).
	// Examples: "keys/jwt-rsa.pem", "keys/jwt-ec.pem"
	SigningKeyFile string `json:"signing_key_file,omitempty" yaml:"signing_key_file,omitempty"`

	// SigningMethod specifies the JWT signing algorithm.
	// Supported: "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "ES256", "ES384", "ES512"
	// Examples: "HS256", "RS256"
	// Default: "HS256"
	SigningMethod string `json:"signing_method,omitempty" yaml:"signing_method,omitempty"`

	// TokenLookup specifies where to look for the JWT token.
	// Examples: "header:Authorization", "query:token", "form:token", "cookie:token"
	// Default: "header:Authorization"
	TokenLookup string `json:"token_lookup,omitempty" yaml:"token_lookup,omitempty"`

	// TokenPrefix specifies the prefix to strip from the token value.
	// Examples: "Bearer ", "Token ", "" (no prefix)
	// Default: "Bearer "
	TokenPrefix string `json:"token_prefix,omitempty" yaml:"token_prefix,omitempty"`

	// Validation CEL expression for additional token/claims validation.
	// Available variables: token (jwt.Token), claims (jwt.MapClaims), context (echo.Context)
	// Examples: 'claims.exp > now()', 'claims.aud == "api" && claims.iss == "myapp"'
	Validation string `json:"validation,omitempty" yaml:"validation,omitempty"`

	// ErrorHandler handles JWT validation errors.
	// Cannot be serialized to JSON/YAML, must be set programmatically.
	// Default: returns HTTP 401 Unauthorized
	ErrorHandler func(error, echo.Context) error `json:"-" yaml:"-"`

	// SuccessHandler handles successful JWT validation.
	// Cannot be serialized to JSON/YAML, must be set programmatically.
	// Default: stores user claims in context and continues
	SuccessHandler func(echo.Context) error `json:"-" yaml:"-"`
}

JWTAuthConfig configures JWT (JSON Web Token) authentication middleware. JWT middleware provides stateless authentication using signed tokens with configurable validation.

type KeyAuthConfig

type KeyAuthConfig struct {
	// KeyLookup specifies where to look for the API key.
	// Examples: "header:X-API-Key", "query:api_key", "form:api_key", "header:Authorization"
	// Default: "header:Authorization"
	KeyLookup string `json:"key_lookup,omitempty" yaml:"key_lookup,omitempty"`

	// AuthScheme sets the authentication scheme for Authorization header.
	// Examples: "Bearer", "Token", "" (no scheme)
	// Default: "Bearer"
	AuthScheme string `json:"auth_scheme,omitempty" yaml:"auth_scheme,omitempty"`

	// Validator is a function that validates the provided API key.
	// Cannot be serialized to JSON/YAML, must be set programmatically.
	// Example: func(key string, c echo.Context) (bool, error) {
	//   return key == "valid-api-key", nil
	// }
	Validator func(string, echo.Context) (bool, error) `json:"-" yaml:"-"`

	// ErrorHandler handles authentication errors.
	// Cannot be serialized to JSON/YAML, must be set programmatically.
	// Default: returns HTTP 401 Unauthorized
	ErrorHandler func(error, echo.Context) error `json:"-" yaml:"-"`
}

KeyAuthConfig configures API Key Authentication middleware. KeyAuth middleware provides authentication using API keys from headers, query parameters, or forms. See: https://echo.labstack.com/docs/middleware/key-auth

type LoggerConfig

type LoggerConfig struct {
	// Format defines the log format template using Echo's template syntax.
	// Available variables: time_unix, time_rfc3339, remote_ip, uri, host, method, status, error, latency, bytes_in, bytes_out
	// Examples: "${method} ${uri} ${status} ${latency_human}\n"
	//           "{\"time\":\"${time_rfc3339}\",\"method\":\"${method}\",\"uri\":\"${uri}\",\"status\":${status}}\n"
	// Default: JSON format with comprehensive request details
	Format string `json:"format,omitempty" yaml:"format,omitempty"`

	// CustomTimeFormat specifies a custom time format for ${time_custom} variable.
	// Uses Go's time format layout ("2006-01-02 15:04:05").
	// Examples: "2006-01-02 15:04:05", "Jan _2 15:04:05"
	// Default: ""
	CustomTimeFormat string `json:"custom_time_format,omitempty" yaml:"custom_time_format,omitempty"`

	// Output specifies the output destination for log messages (io.Writer).
	// Cannot be serialized to JSON/YAML, must be set programmatically.
	// Examples: os.Stdout, os.Stderr, file handle
	// Default: os.Stdout
	Output interface{} `json:"-" yaml:"-"`

	// Template is deprecated in favor of Format field.
	// Kept for backwards compatibility.
	Template string `json:"template,omitempty" yaml:"template,omitempty"`

	// CustomTags allows adding custom variables to the log format.
	// Examples: map[string]string{"app": "myapp", "version": "1.0.0"}
	// Default: nil
	CustomTags map[string]string `json:"custom_tags,omitempty" yaml:"custom_tags,omitempty"`
}

LoggerConfig configures request logging middleware. The Logger middleware logs HTTP requests with customizable format and output. See: https://echo.labstack.com/docs/middleware/logger

type MethodOverrideConfig

type MethodOverrideConfig struct {
	Getter func(echo.Context) string `json:"-"` // Method getter function, not serializable
}

MethodOverrideConfig configures MethodOverride middleware

type MiddlewareConfig

type MiddlewareConfig struct {
	// Core middleware - Essential middleware for most applications
	CORS      *CORSConfig      `json:"cors,omitempty" yaml:"cors,omitempty"`             // Cross-Origin Resource Sharing
	Logger    *LoggerConfig    `json:"logger,omitempty" yaml:"logger,omitempty"`         // Request logging
	Recover   *RecoverConfig   `json:"recover,omitempty" yaml:"recover,omitempty"`       // Panic recovery
	RequestID *RequestIDConfig `json:"request_id,omitempty" yaml:"request_id,omitempty"` // Request ID generation

	// Security middleware - Authentication and authorization
	BasicAuth *BasicAuthConfig `json:"basic_auth,omitempty" yaml:"basic_auth,omitempty"` // HTTP Basic Authentication
	JWTAuth   *JWTAuthConfig   `json:"jwt_auth,omitempty" yaml:"jwt_auth,omitempty"`     // JWT Token Authentication
	KeyAuth   *KeyAuthConfig   `json:"key_auth,omitempty" yaml:"key_auth,omitempty"`     // API Key Authentication
	CSRF      *CSRFConfig      `json:"csrf,omitempty" yaml:"csrf,omitempty"`             // Cross-Site Request Forgery protection
	Secure    *SecureConfig    `json:"secure,omitempty" yaml:"secure,omitempty"`         // Security headers (XSS, HSTS, etc.)

	// Request/Response interceptors - CEL-powered processing
	Interceptors []*InterceptorConfig `json:"interceptors,omitempty" yaml:"interceptors,omitempty"` // Generic request/response interceptors

	// Request/Response processing middleware - Content handling
	BodyDump   *BodyDumpConfig   `json:"body_dump,omitempty" yaml:"body_dump,omitempty"`   // Request/response body logging
	BodyLimit  *BodyLimitConfig  `json:"body_limit,omitempty" yaml:"body_limit,omitempty"` // Request body size limiting
	Gzip       *GzipConfig       `json:"gzip,omitempty" yaml:"gzip,omitempty"`             // Response compression
	Decompress *DecompressConfig `json:"decompress,omitempty" yaml:"decompress,omitempty"` // Request decompression

	// Routing and static middleware - URL and file handling
	Static         *StaticConfig         `json:"static,omitempty" yaml:"static,omitempty"`                   // Static file serving
	MethodOverride *MethodOverrideConfig `json:"method_override,omitempty" yaml:"method_override,omitempty"` // HTTP method override
	Proxy          *ProxyConfig          `json:"proxy,omitempty" yaml:"proxy,omitempty"`                     // Reverse proxy
	Rewrite        *RewriteConfig        `json:"rewrite,omitempty" yaml:"rewrite,omitempty"`                 // URL rewriting

	// Redirect middleware - URL redirection
	HTTPSRedirect    *RedirectConfig `json:"https_redirect,omitempty" yaml:"https_redirect,omitempty"`         // HTTP to HTTPS redirect
	WWWRedirect      *RedirectConfig `json:"www_redirect,omitempty" yaml:"www_redirect,omitempty"`             // WWW subdomain redirect
	HTTPSWWWRedirect *RedirectConfig `json:"https_www_redirect,omitempty" yaml:"https_www_redirect,omitempty"` // Combined HTTPS+WWW redirect

	// URL normalization middleware - Trailing slash handling
	AddTrailingSlash    *TrailingSlashConfig `json:"add_trailing_slash,omitempty" yaml:"add_trailing_slash,omitempty"`       // Add trailing slash to URLs
	RemoveTrailingSlash *TrailingSlashConfig `json:"remove_trailing_slash,omitempty" yaml:"remove_trailing_slash,omitempty"` // Remove trailing slash from URLs

	// Rate limiting and timeout middleware - Performance and reliability
	RateLimiter    *RateLimiterConfig    `json:"rate_limiter,omitempty" yaml:"rate_limiter,omitempty"`       // Request rate limiting
	Timeout        *TimeoutConfig        `json:"timeout,omitempty" yaml:"timeout,omitempty"`                 // Request timeout
	ContextTimeout *ContextTimeoutConfig `json:"context_timeout,omitempty" yaml:"context_timeout,omitempty"` // Context-based timeout

	// Advanced logging middleware - Structured logging
	RequestLogger *RequestLoggerConfig `json:"request_logger,omitempty" yaml:"request_logger,omitempty"` // Advanced structured logging
}

MiddlewareConfig contains configuration for all available Echo middleware. This struct provides a unified way to configure all Echo v4 middleware types through either programmatic configuration or YAML/JSON file loading.

func CompressionConfig

func CompressionConfig() MiddlewareConfig

CompressionConfig returns a MiddlewareConfig focused on compression and performance

func DefaultConfig

func DefaultConfig() MiddlewareConfig

DefaultConfig returns a MiddlewareConfig with sensible defaults

func DevelopmentConfig

func DevelopmentConfig() MiddlewareConfig

DevelopmentConfig returns a MiddlewareConfig suitable for development

func LoadConfigFromYAML

func LoadConfigFromYAML(filename string) (MiddlewareConfig, error)

LoadConfigFromYAML loads middleware configuration from a YAML file. This function reads and parses a YAML file containing middleware configuration, validates the parsed data, and returns a MiddlewareConfig struct.

Example usage:

config, err := middleware.LoadConfigFromYAML("config/middleware.yaml")
if err != nil {
  log.Fatalf("Failed to load config: %v", err)
}

Parameters:

filename - Path to the YAML configuration file

Returns:

MiddlewareConfig - Parsed and validated configuration
error - Any error that occurred during loading or validation

func MinimalConfig

func MinimalConfig() MiddlewareConfig

MinimalConfig returns a MiddlewareConfig with only essential middleware

func ProductionConfig

func ProductionConfig() MiddlewareConfig

ProductionConfig returns a MiddlewareConfig suitable for production use

func ProxyGatewayConfig

func ProxyGatewayConfig() MiddlewareConfig

ProxyGatewayConfig returns a MiddlewareConfig for proxy/gateway scenarios

func SecurityConfig

func SecurityConfig() MiddlewareConfig

SecurityConfig returns a MiddlewareConfig focused on security middleware

type ProxyConfig

type ProxyConfig struct {
	Targets        []*ProxyTarget             `json:"targets,omitempty"`       // List of targets
	Balancer       interface{}                `json:"-"`                       // Load balancer, not serializable
	Rewrite        map[string]string          `json:"rewrite,omitempty"`       // URL rewrite rules
	RegexRewrite   map[string]string          `json:"regex_rewrite,omitempty"` // Regex rewrite rules
	Timeout        time.Duration              `json:"timeout,omitempty"`       // Request timeout
	ModifyResponse func(*http.Response) error `json:"-"`                       // Response modifier, not serializable
}

ProxyConfig configures Proxy middleware

type ProxyTarget

type ProxyTarget struct {
	Name string `json:"name,omitempty"`
	URL  string `json:"url"`
}

ProxyTarget represents a proxy target

type RateLimiterConfig

type RateLimiterConfig struct {
	// RequestsPerSecond sets the rate limit as requests per second.
	// Examples: 10.0 (10 req/s), 100.0 (100 req/s), 0.1 (1 req per 10s)
	// Default: 20.0
	RequestsPerSecond float64 `json:"requests_per_second" yaml:"requests_per_second"`

	// Burst sets the maximum burst size (number of requests that can exceed the rate).
	// Examples: 30 (allow bursts up to 30), 1 (strict rate limiting)
	// Default: RequestsPerSecond * 1.5
	Burst int `json:"burst" yaml:"burst"`

	// ExpiresIn sets how long rate limit entries are kept in memory.
	// Examples: 5*time.Minute, 1*time.Hour
	// YAML format: "5m", "1h", "30s"
	// Default: 5 minutes
	ExpiresIn time.Duration `json:"expires_in,omitempty" yaml:"expires_in,omitempty"`
}

RateLimiterConfig configures request rate limiting middleware. RateLimiter controls the rate of requests to prevent abuse and ensure fair usage. See: https://echo.labstack.com/docs/middleware/rate-limiter

type RecoverConfig

type RecoverConfig struct {
	// StackSize sets the maximum size of the stack trace in bytes.
	// Examples: 4096 (4KB), 8192 (8KB)
	// Default: 4KB
	StackSize int `json:"stack_size,omitempty" yaml:"stack_size,omitempty"`

	// DisableStackAll disables printing stack trace of all goroutines.
	// Examples: true (show only current goroutine), false (show all)
	// Default: false
	DisableStackAll bool `json:"disable_stack_all,omitempty" yaml:"disable_stack_all,omitempty"`

	// DisablePrintStack disables printing the stack trace.
	// Examples: true (no stack trace), false (print stack trace)
	// Default: false
	DisablePrintStack bool `json:"disable_print_stack,omitempty" yaml:"disable_print_stack,omitempty"`

	// DisableErrorHandler disables the centralized error handler for panics.
	// Examples: true (handle panics inline), false (use global error handler)
	// Default: false
	DisableErrorHandler bool `json:"disable_error_handler,omitempty" yaml:"disable_error_handler,omitempty"`
}

RecoverConfig configures panic recovery middleware. Recover middleware recovers from panics anywhere in the chain and handles them gracefully. See: https://echo.labstack.com/docs/middleware/recover

type RedirectConfig

type RedirectConfig struct {
	Code int `json:"code,omitempty"` // HTTP redirect status code (301, 302, etc.)
}

RedirectConfig configures redirect middleware (HTTPSRedirect, WWWRedirect, etc.)

type RequestIDConfig

type RequestIDConfig struct {
	// Generator is a function that generates unique request IDs.
	// Cannot be serialized to JSON/YAML, must be set programmatically.
	// Default: generates random 32-character hex string
	Generator func() string `json:"-" yaml:"-"`

	// TargetHeader specifies which header to store the request ID in.
	// Examples: "X-Request-ID", "X-Correlation-ID", "X-Trace-ID"
	// Default: "X-Request-Id"
	TargetHeader string `json:"target_header,omitempty" yaml:"target_header,omitempty"`

	// Handler is a function called after the request ID is generated.
	// Cannot be serialized to JSON/YAML, must be set programmatically.
	// Default: nil
	Handler func(echo.Context, string) `json:"-" yaml:"-"`
}

RequestIDConfig configures request ID generation middleware. RequestID generates a unique identifier for each request for tracing and logging. See: https://echo.labstack.com/docs/middleware/request-id

type RequestLoggerConfig

type RequestLoggerConfig struct {
	LogStatus        bool                                                     `json:"log_status,omitempty"`
	LogURI           bool                                                     `json:"log_uri,omitempty"`
	LogError         bool                                                     `json:"log_error,omitempty"`
	LogLatency       bool                                                     `json:"log_latency,omitempty"`
	LogProtocol      bool                                                     `json:"log_protocol,omitempty"`
	LogRemoteIP      bool                                                     `json:"log_remote_ip,omitempty"`
	LogHost          bool                                                     `json:"log_host,omitempty"`
	LogMethod        bool                                                     `json:"log_method,omitempty"`
	LogUserAgent     bool                                                     `json:"log_user_agent,omitempty"`
	LogRequestID     bool                                                     `json:"log_request_id,omitempty"`
	LogReferer       bool                                                     `json:"log_referer,omitempty"`
	LogContentLength bool                                                     `json:"log_content_length,omitempty"`
	LogResponseSize  bool                                                     `json:"log_response_size,omitempty"`
	HandleError      bool                                                     `json:"handle_error,omitempty"`
	LogValuesFunc    func(echo.Context, middleware.RequestLoggerValues) error `json:"-"` // Log values function, not serializable
}

RequestLoggerConfig configures RequestLogger middleware

type RewriteConfig

type RewriteConfig struct {
	Rules map[string]string `json:"rules,omitempty"` // URL rewrite rules (from -> to)
}

RewriteConfig configures Rewrite middleware

type SecureConfig

type SecureConfig struct {
	// XSSProtection sets the X-XSS-Protection header to prevent XSS attacks.
	// Examples: "1; mode=block", "1", "0"
	// Default: "1; mode=block"
	XSSProtection string `json:"xss_protection,omitempty" yaml:"xss_protection,omitempty"`

	// ContentTypeNosniff sets the X-Content-Type-Options header.
	// Examples: "nosniff"
	// Default: "nosniff"
	ContentTypeNosniff string `json:"content_type_nosniff,omitempty" yaml:"content_type_nosniff,omitempty"`

	// XFrameOptions sets the X-Frame-Options header to prevent clickjacking.
	// Examples: "DENY", "SAMEORIGIN", "ALLOW-FROM https://example.com"
	// Default: "SAMEORIGIN"
	XFrameOptions string `json:"x_frame_options,omitempty" yaml:"x_frame_options,omitempty"`

	// HSTSMaxAge sets the max-age value for the Strict-Transport-Security header (seconds).
	// Examples: 31536000 (1 year), 63072000 (2 years)
	// Default: 0 (disabled)
	HSTSMaxAge int `json:"hsts_max_age,omitempty" yaml:"hsts_max_age,omitempty"`

	// HSTSExcludeSubdomains excludes subdomains from HSTS policy.
	// Examples: true (exclude subdomains), false (include subdomains)
	// Default: false
	HSTSExcludeSubdomains bool `json:"hsts_exclude_subdomains,omitempty" yaml:"hsts_exclude_subdomains,omitempty"`

	// ContentSecurityPolicy sets the Content-Security-Policy header.
	// Examples: "default-src 'self'", "default-src 'self'; script-src 'self' 'unsafe-inline'"
	// Default: ""
	ContentSecurityPolicy string `json:"content_security_policy,omitempty" yaml:"content_security_policy,omitempty"`

	// CSPReportOnly sets Content-Security-Policy-Report-Only instead of CSP.
	// Examples: true (report only), false (enforce policy)
	// Default: false
	CSPReportOnly bool `json:"csp_report_only,omitempty" yaml:"csp_report_only,omitempty"`

	// HSTSPreloadEnabled adds the preload directive to HSTS header.
	// Examples: true (enable preload), false (disable preload)
	// Default: false
	HSTSPreloadEnabled bool `json:"hsts_preload_enabled,omitempty" yaml:"hsts_preload_enabled,omitempty"`

	// ReferrerPolicy sets the Referrer-Policy header.
	// Examples: "no-referrer", "strict-origin", "same-origin"
	// Default: ""
	ReferrerPolicy string `json:"referrer_policy,omitempty" yaml:"referrer_policy,omitempty"`
}

SecureConfig configures security headers middleware. Secure middleware adds various security headers to protect against common attacks. See: https://echo.labstack.com/docs/middleware/secure

type StaticConfig

type StaticConfig struct {
	Root       string          `json:"root,omitempty"`        // Root directory for static files
	Index      string          `json:"index,omitempty"`       // Index file name
	Browse     bool            `json:"browse,omitempty"`      // Enable directory browsing
	HTML5      bool            `json:"html5,omitempty"`       // Enable HTML5 mode
	IgnoreBase bool            `json:"ignore_base,omitempty"` // Ignore base of URL path
	Filesystem http.FileSystem `json:"-"`                     // Custom filesystem, not serializable
}

StaticConfig configures Static middleware

type TimeoutConfig

type TimeoutConfig struct {
	// Timeout sets the maximum duration for request processing.
	// Examples: 30*time.Second, 5*time.Minute
	// YAML format: "30s", "5m", "1h"
	// Default: 30 seconds
	Timeout time.Duration `json:"timeout" yaml:"timeout"`
}

TimeoutConfig configures request timeout middleware. Timeout middleware cancels requests that take longer than the specified duration. See: https://echo.labstack.com/docs/middleware/timeout

type TrailingSlashConfig

type TrailingSlashConfig struct {
	RedirectCode int `json:"redirect_code,omitempty"` // HTTP redirect status code (default 301)
}

TrailingSlashConfig configures TrailingSlash middleware

type User

type User struct {
	Username string
	Password string
	Hash     string // For htpasswd files
}

User represents a user with credentials

type UserStore

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

UserStore manages user credentials from various sources

func NewUserStore

func NewUserStore() *UserStore

NewUserStore creates a new user store

func (*UserStore) AddUser

func (us *UserStore) AddUser(username, password string)

AddUser adds a user with plain password (for testing or dynamic user management)

func (*UserStore) AddUserWithHash

func (us *UserStore) AddUserWithHash(username, hash string)

AddUserWithHash adds a user with pre-hashed password (for testing or dynamic user management)

func (*UserStore) Clear

func (us *UserStore) Clear()

Clear removes all users from the store

func (*UserStore) GetUser

func (us *UserStore) GetUser(username string) (*User, bool)

GetUser retrieves user information by username

func (*UserStore) ListUsers

func (us *UserStore) ListUsers() []string

ListUsers returns a list of all usernames

func (*UserStore) LoadHtpasswdFile

func (us *UserStore) LoadHtpasswdFile(filename string) error

LoadHtpasswdFile loads users from an Apache htpasswd file Supports bcrypt, SHA1, and MD5 password hashing

func (*UserStore) LoadUserpassFile

func (us *UserStore) LoadUserpassFile(filename string) error

LoadUserpassFile loads users from a simple user=password text file

func (*UserStore) RemoveUser

func (us *UserStore) RemoveUser(username string)

RemoveUser removes a user from the store

func (*UserStore) UserCount

func (us *UserStore) UserCount() int

UserCount returns the number of users in the store

func (*UserStore) ValidateUser

func (us *UserStore) ValidateUser(username, password string) (bool, error)

ValidateUser validates username and password against stored credentials

Jump to

Keyboard shortcuts

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