middleware

package
v5.0.0-...-ec5b858 Latest Latest
Warning

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

Go to latest
Published: Jul 22, 2023 License: MIT Imports: 30 Imported by: 79

Documentation

Index

Constants

View Source
const (

	// KB is 1 KiloByte = 1024 bytes
	KB
	// MB is 1 Megabyte = 1_048_576 bytes
	MB
	// GB is 1 Gigabyte = 1_073_741_824 bytes
	GB
	// TB is 1 Terabyte = 1_099_511_627_776 bytes
	TB
	// PB is 1 Petabyte = 1_125_899_906_842_624 bytes
	PB
	// EB is 1 Exabyte = 1_152_921_504_606_847_000 bytes
	EB
)
View Source
const GZIPEncoding string = "gzip"

GZIPEncoding content-encoding header if set to "gzip", decompress body contents.

View Source
const StatusCodeContextCanceled = 499

StatusCodeContextCanceled is a custom HTTP status code for situations where a client unexpectedly closed the connection to the server. As there is no standard error code for "client closed connection", but various well-known HTTP clients and server implement this HTTP code we use 499 too instead of the more problematic 5xx, which does not allow to detect this situation

Variables

View Source
var DefaultCORSConfig = CORSConfig{
	Skipper:      DefaultSkipper,
	AllowOrigins: []string{"*"},
	AllowMethods: []string{http.MethodGet, http.MethodHead, http.MethodPut, http.MethodPatch, http.MethodPost, http.MethodDelete},
}

DefaultCORSConfig is the default CORS middleware config.

View Source
var DefaultCSRFConfig = CSRFConfig{
	Skipper:        DefaultSkipper,
	TokenLength:    32,
	TokenLookup:    "header:" + echo.HeaderXCSRFToken,
	ContextKey:     "csrf",
	CookieName:     "_csrf",
	CookieMaxAge:   86400,
	CookieSameSite: http.SameSiteDefaultMode,
}

DefaultCSRFConfig is the default CSRF middleware config.

View Source
var DefaultKeyAuthConfig = KeyAuthConfig{
	Skipper:   DefaultSkipper,
	KeyLookup: "header:" + echo.HeaderAuthorization + ":Bearer ",
}

DefaultKeyAuthConfig is the default KeyAuth middleware config.

View Source
var DefaultLoggerConfig = LoggerConfig{
	Skipper: DefaultSkipper,
	Format: `{"time":"${time_rfc3339_nano}","level":"INFO","id":"${id}","remote_ip":"${remote_ip}",` +
		`"host":"${host}","method":"${method}","uri":"${uri}","user_agent":"${user_agent}",` +
		`"status":${status},"error":"${error}","latency":${latency},"latency_human":"${latency_human}"` +
		`,"bytes_in":${bytes_in},"bytes_out":${bytes_out}}` + "\n",
	CustomTimeFormat: "2006-01-02 15:04:05.00000",
}

DefaultLoggerConfig is the default Logger middleware config.

View Source
var DefaultMethodOverrideConfig = MethodOverrideConfig{
	Skipper: DefaultSkipper,
	Getter:  MethodFromHeader(echo.HeaderXHTTPMethodOverride),
}

DefaultMethodOverrideConfig is the default MethodOverride middleware config.

View Source
var DefaultProxyConfig = ProxyConfig{
	Skipper:    DefaultSkipper,
	ContextKey: "target",
}

DefaultProxyConfig is the default Proxy middleware config.

View Source
var DefaultRateLimiterConfig = RateLimiterConfig{
	Skipper: DefaultSkipper,
	IdentifierExtractor: func(ctx echo.Context) (string, error) {
		id := ctx.RealIP()
		return id, nil
	},
	ErrorHandler: func(c echo.Context, err error) error {
		return &echo.HTTPError{
			Code:     ErrExtractorError.Code,
			Message:  ErrExtractorError.Message,
			Internal: err,
		}
	},
	DenyHandler: func(c echo.Context, identifier string, err error) error {
		return &echo.HTTPError{
			Code:     ErrRateLimitExceeded.Code,
			Message:  ErrRateLimitExceeded.Message,
			Internal: err,
		}
	},
}

DefaultRateLimiterConfig defines default values for RateLimiterConfig

View Source
var DefaultRateLimiterMemoryStoreConfig = RateLimiterMemoryStoreConfig{
	ExpiresIn: 3 * time.Minute,
}

DefaultRateLimiterMemoryStoreConfig provides default configuration values for RateLimiterMemoryStore

View Source
var DefaultRecoverConfig = RecoverConfig{
	Skipper:           DefaultSkipper,
	StackSize:         4 << 10,
	DisableStackAll:   false,
	DisablePrintStack: false,
}

DefaultRecoverConfig is the default Recover middleware config.

View Source
var DefaultSecureConfig = SecureConfig{
	Skipper:            DefaultSkipper,
	XSSProtection:      "1; mode=block",
	ContentTypeNosniff: "nosniff",
	XFrameOptions:      "SAMEORIGIN",
	HSTSPreloadEnabled: false,
}

DefaultSecureConfig is the default Secure middleware config.

View Source
var DefaultStaticConfig = StaticConfig{
	Skipper: DefaultSkipper,
	Index:   "index.html",
}

DefaultStaticConfig is the default Static middleware config.

View Source
var ErrCSRFInvalid = echo.NewHTTPError(http.StatusForbidden, "invalid csrf token")

ErrCSRFInvalid is returned when CSRF check fails

View Source
var ErrExtractorError = echo.NewHTTPError(http.StatusForbidden, "error while extracting identifier")

ErrExtractorError denotes an error raised when extractor function is unsuccessful

View Source
var ErrInvalidKey = echo.NewHTTPError(http.StatusUnauthorized, "invalid key")

ErrInvalidKey denotes an error raised when key value is invalid by validator

View Source
var ErrKeyMissing = echo.NewHTTPError(http.StatusUnauthorized, "missing key")

ErrKeyMissing denotes an error raised when key value could not be extracted from request

View Source
var ErrRateLimitExceeded = echo.NewHTTPError(http.StatusTooManyRequests, "rate limit exceeded")

ErrRateLimitExceeded denotes an error raised when rate limit is exceeded

View Source
var RedirectHTTPSConfig = RedirectConfig{/* contains filtered or unexported fields */}

RedirectHTTPSConfig is the HTTPS Redirect middleware config.

View Source
var RedirectHTTPSWWWConfig = RedirectConfig{/* contains filtered or unexported fields */}

RedirectHTTPSWWWConfig is the HTTPS WWW Redirect middleware config.

View Source
var RedirectNonHTTPSWWWConfig = RedirectConfig{/* contains filtered or unexported fields */}

RedirectNonHTTPSWWWConfig is the non HTTPS WWW Redirect middleware config.

View Source
var RedirectNonWWWConfig = RedirectConfig{/* contains filtered or unexported fields */}

RedirectNonWWWConfig is the non WWW Redirect middleware config.

View Source
var RedirectWWWConfig = RedirectConfig{/* contains filtered or unexported fields */}

RedirectWWWConfig is the WWW Redirect middleware config.

Functions

func AddTrailingSlash

func AddTrailingSlash() echo.MiddlewareFunc

AddTrailingSlash returns a root level (before router) middleware which adds a trailing slash to the request `URL#Path`.

Usage `Echo#Pre(AddTrailingSlash())`

func AddTrailingSlashWithConfig

func AddTrailingSlashWithConfig(config AddTrailingSlashConfig) echo.MiddlewareFunc

AddTrailingSlashWithConfig returns an AddTrailingSlash middleware with config or panics on invalid configuration.

func BasicAuth

func BasicAuth(fn BasicAuthValidator) echo.MiddlewareFunc

BasicAuth returns an BasicAuth middleware.

For valid credentials it calls the next handler. For missing or invalid credentials, it sends "401 - Unauthorized" response.

func BasicAuthWithConfig

func BasicAuthWithConfig(config BasicAuthConfig) echo.MiddlewareFunc

BasicAuthWithConfig returns an BasicAuthWithConfig middleware with config.

func BodyDump

func BodyDump(handler BodyDumpHandler) echo.MiddlewareFunc

BodyDump returns a BodyDump middleware.

BodyDump middleware captures the request and response payload and calls the registered handler.

func BodyDumpWithConfig

func BodyDumpWithConfig(config BodyDumpConfig) echo.MiddlewareFunc

BodyDumpWithConfig returns a BodyDump middleware with config. See: `BodyDump()`.

func BodyLimit

func BodyLimit(limitBytes int64) echo.MiddlewareFunc

BodyLimit returns a BodyLimit middleware.

BodyLimit middleware sets the maximum allowed size for a request body, if the size exceeds the configured limit, it sends "413 - Request Entity Too Large" response. The BodyLimit is determined based on both `Content-Length` request header and actual content read, which makes it super secure.

func BodyLimitWithConfig

func BodyLimitWithConfig(config BodyLimitConfig) echo.MiddlewareFunc

BodyLimitWithConfig returns a BodyLimitWithConfig middleware. Middleware sets the maximum allowed size in bytes for a request body, if the size exceeds the configured limit, it sends "413 - Request Entity Too Large" response. The BodyLimitWithConfig is determined based on both `Content-Length` request header and actual content read, which makes it super secure.

func CORS

func CORS() echo.MiddlewareFunc

CORS returns a Cross-Origin Resource Sharing (CORS) middleware. See also MDN: Cross-Origin Resource Sharing (CORS).

Security: Poorly configured CORS can compromise security because it allows relaxation of the browser's Same-Origin policy. See Exploiting CORS misconfigurations for Bitcoins and bounties and Portswigger: Cross-origin resource sharing (CORS) for more details.

func CORSWithConfig

func CORSWithConfig(config CORSConfig) echo.MiddlewareFunc

CORSWithConfig returns a CORS middleware with config or panics on invalid configuration. See: CORS.

func CSRF

func CSRF() echo.MiddlewareFunc

CSRF returns a Cross-Site Request Forgery (CSRF) middleware. See: https://en.wikipedia.org/wiki/Cross-site_request_forgery

func CSRFWithConfig

func CSRFWithConfig(config CSRFConfig) echo.MiddlewareFunc

CSRFWithConfig returns a CSRF middleware with config or panics on invalid configuration.

func ContextTimeout

func ContextTimeout(timeout time.Duration) echo.MiddlewareFunc

ContextTimeout returns a middleware which returns error (503 Service Unavailable error) to client when underlying method returns context.DeadlineExceeded error.

func ContextTimeoutWithConfig

func ContextTimeoutWithConfig(config ContextTimeoutConfig) echo.MiddlewareFunc

ContextTimeoutWithConfig returns a Timeout middleware with config.

func Decompress

func Decompress() echo.MiddlewareFunc

Decompress decompresses request body based if content encoding type is set to "gzip" with default config

func DecompressWithConfig

func DecompressWithConfig(config DecompressConfig) echo.MiddlewareFunc

DecompressWithConfig returns a decompress middleware with config or panics on invalid configuration.

func DefaultSkipper

func DefaultSkipper(echo.Context) bool

DefaultSkipper returns false which processes the middleware.

func Gzip

func Gzip() echo.MiddlewareFunc

Gzip returns a middleware which compresses HTTP response using gzip compression scheme.

func GzipWithConfig

func GzipWithConfig(config GzipConfig) echo.MiddlewareFunc

GzipWithConfig returns a middleware which compresses HTTP response using gzip compression scheme.

func HTTPSNonWWWRedirect

func HTTPSNonWWWRedirect() echo.MiddlewareFunc

HTTPSNonWWWRedirect redirects http requests to https non www. For example, http://www.labstack.com will be redirect to https://labstack.com.

Usage `Echo#Pre(HTTPSNonWWWRedirect())`

func HTTPSNonWWWRedirectWithConfig

func HTTPSNonWWWRedirectWithConfig(config RedirectConfig) echo.MiddlewareFunc

HTTPSNonWWWRedirectWithConfig returns a HTTPS Non-WWW redirect middleware with config or panics on invalid configuration.

func HTTPSRedirect

func HTTPSRedirect() echo.MiddlewareFunc

HTTPSRedirect redirects http requests to https. For example, http://labstack.com will be redirect to https://labstack.com.

Usage `Echo#Pre(HTTPSRedirect())`

func HTTPSRedirectWithConfig

func HTTPSRedirectWithConfig(config RedirectConfig) echo.MiddlewareFunc

HTTPSRedirectWithConfig returns a HTTPS redirect middleware with config or panics on invalid configuration.

func HTTPSWWWRedirect

func HTTPSWWWRedirect() echo.MiddlewareFunc

HTTPSWWWRedirect redirects http requests to https www. For example, http://labstack.com will be redirect to https://www.labstack.com.

Usage `Echo#Pre(HTTPSWWWRedirect())`

func HTTPSWWWRedirectWithConfig

func HTTPSWWWRedirectWithConfig(config RedirectConfig) echo.MiddlewareFunc

HTTPSWWWRedirectWithConfig returns a HTTPS WWW redirect middleware with config or panics on invalid configuration.

func KeyAuth

func KeyAuth(fn KeyAuthValidator) echo.MiddlewareFunc

KeyAuth returns an KeyAuth middleware.

For valid key it calls the next handler. For invalid key, it sends "401 - Unauthorized" response. For missing key, it sends "400 - Bad Request" response.

func KeyAuthWithConfig

func KeyAuthWithConfig(config KeyAuthConfig) echo.MiddlewareFunc

KeyAuthWithConfig returns an KeyAuth middleware or panics if configuration is invalid.

For first valid key it calls the next handler. For invalid key, it sends "401 - Unauthorized" response. For missing key, it sends "400 - Bad Request" response.

func Logger

func Logger() echo.MiddlewareFunc

Logger returns a middleware that logs HTTP requests.

func LoggerWithConfig

func LoggerWithConfig(config LoggerConfig) echo.MiddlewareFunc

LoggerWithConfig returns a Logger middleware with config or panics on invalid configuration.

func MethodOverride

func MethodOverride() echo.MiddlewareFunc

MethodOverride returns a MethodOverride middleware. MethodOverride middleware checks for the overridden method from the request and uses it instead of the original method.

For security reasons, only `POST` method can be overridden.

func MethodOverrideWithConfig

func MethodOverrideWithConfig(config MethodOverrideConfig) echo.MiddlewareFunc

MethodOverrideWithConfig returns a Method Override middleware with config or panics on invalid configuration.

func NonWWWRedirect

func NonWWWRedirect() echo.MiddlewareFunc

NonWWWRedirect redirects www requests to non www. For example, http://www.labstack.com will be redirect to http://labstack.com.

Usage `Echo#Pre(NonWWWRedirect())`

func NonWWWRedirectWithConfig

func NonWWWRedirectWithConfig(config RedirectConfig) echo.MiddlewareFunc

NonWWWRedirectWithConfig returns a Non-WWW redirect middleware with config or panics on invalid configuration.

func Proxy

func Proxy(balancer ProxyBalancer) echo.MiddlewareFunc

Proxy returns a Proxy middleware.

Proxy middleware forwards the request to upstream server using a configured load balancing technique.

func ProxyWithConfig

func ProxyWithConfig(config ProxyConfig) echo.MiddlewareFunc

ProxyWithConfig returns a Proxy middleware or panics if configuration is invalid.

Proxy middleware forwards the request to upstream server using a configured load balancing technique.

func RateLimiter

func RateLimiter(store RateLimiterStore) echo.MiddlewareFunc

RateLimiter returns a rate limiting middleware

e := echo.New()

limiterStore := middleware.NewRateLimiterMemoryStore(20)

e.GET("/rate-limited", func(c echo.Context) error {
	return c.String(http.StatusOK, "test")
}, RateLimiter(limiterStore))

func RateLimiterWithConfig

func RateLimiterWithConfig(config RateLimiterConfig) echo.MiddlewareFunc

RateLimiterWithConfig returns a rate limiting middleware

e := echo.New()

config := middleware.RateLimiterConfig{
	Skipper: DefaultSkipper,
	Store: middleware.NewRateLimiterMemoryStore(
		middleware.RateLimiterMemoryStoreConfig{Rate: 10, Burst: 30, ExpiresIn: 3 * time.Minute}
	)
	IdentifierExtractor: func(ctx echo.Context) (string, error) {
		id := ctx.RealIP()
		return id, nil
	},
	ErrorHandler: func(context echo.Context, err error) error {
		return context.JSON(http.StatusTooManyRequests, nil)
	},
	DenyHandler: func(context echo.Context, identifier string) error {
		return context.JSON(http.StatusForbidden, nil)
	},
}

e.GET("/rate-limited", func(c echo.Context) error {
	return c.String(http.StatusOK, "test")
}, middleware.RateLimiterWithConfig(config))

func Recover

func Recover() echo.MiddlewareFunc

Recover returns a middleware which recovers from panics anywhere in the chain and handles the control to the centralized HTTPErrorHandler.

func RecoverWithConfig

func RecoverWithConfig(config RecoverConfig) echo.MiddlewareFunc

RecoverWithConfig returns a Recovery middleware with config or panics on invalid configuration.

func RemoveTrailingSlash

func RemoveTrailingSlash() echo.MiddlewareFunc

RemoveTrailingSlash returns a root level (before router) middleware which removes a trailing slash from the request URI.

Usage `Echo#Pre(RemoveTrailingSlash())`

func RemoveTrailingSlashWithConfig

func RemoveTrailingSlashWithConfig(config RemoveTrailingSlashConfig) echo.MiddlewareFunc

RemoveTrailingSlashWithConfig returns a RemoveTrailingSlash middleware with config or panics on invalid configuration.

func RequestID

func RequestID() echo.MiddlewareFunc

RequestID returns a X-Request-ID middleware.

func RequestIDWithConfig

func RequestIDWithConfig(config RequestIDConfig) echo.MiddlewareFunc

RequestIDWithConfig returns a X-Request-ID middleware with config or panics on invalid configuration.

func RequestLoggerWithConfig

func RequestLoggerWithConfig(config RequestLoggerConfig) echo.MiddlewareFunc

RequestLoggerWithConfig returns a RequestLogger middleware with config.

func Rewrite

func Rewrite(rules map[string]string) echo.MiddlewareFunc

Rewrite returns a Rewrite middleware.

Rewrite middleware rewrites the URL path based on the provided rules.

func RewriteWithConfig

func RewriteWithConfig(config RewriteConfig) echo.MiddlewareFunc

RewriteWithConfig returns a Rewrite middleware or panics on invalid configuration.

Rewrite middleware rewrites the URL path based on the provided rules.

func Secure

func Secure() echo.MiddlewareFunc

Secure returns a Secure middleware. Secure middleware provides protection against cross-site scripting (XSS) attack, content type sniffing, clickjacking, insecure connection and other code injection attacks.

func SecureWithConfig

func SecureWithConfig(config SecureConfig) echo.MiddlewareFunc

SecureWithConfig returns a Secure middleware with config or panics on invalid configuration.

func Static

func Static(root string) echo.MiddlewareFunc

Static returns a Static middleware to serves static content from the provided root directory.

func StaticWithConfig

func StaticWithConfig(config StaticConfig) echo.MiddlewareFunc

StaticWithConfig returns a Static middleware to serves static content or panics on invalid configuration.

func WWWRedirect

func WWWRedirect() echo.MiddlewareFunc

WWWRedirect redirects non www requests to www. For example, http://labstack.com will be redirect to http://www.labstack.com.

Usage `Echo#Pre(WWWRedirect())`

func WWWRedirectWithConfig

func WWWRedirectWithConfig(config RedirectConfig) echo.MiddlewareFunc

WWWRedirectWithConfig returns a WWW redirect middleware with config or panics on invalid configuration.

Types

type AddTrailingSlashConfig

type AddTrailingSlashConfig struct {
	// Skipper defines a function to skip middleware.
	Skipper Skipper

	// Status code to be used when redirecting the request.
	// Optional, but when provided the request is redirected using this code.
	// Valid status codes: [300...308]
	RedirectCode int
}

AddTrailingSlashConfig is the middleware config for adding trailing slash to the request.

func (AddTrailingSlashConfig) ToMiddleware

func (config AddTrailingSlashConfig) ToMiddleware() (echo.MiddlewareFunc, error)

ToMiddleware converts AddTrailingSlashConfig to middleware or returns an error for invalid configuration

type BasicAuthConfig

type BasicAuthConfig struct {
	// Skipper defines a function to skip middleware.
	Skipper Skipper

	// Validator is a function to validate BasicAuthWithConfig credentials. Note: if request contains multiple basic auth headers
	// this function would be called once for each header until first valid result is returned
	// Required.
	Validator BasicAuthValidator

	// Realm is a string to define realm attribute of BasicAuthWithConfig.
	// Default value "Restricted".
	Realm string
}

BasicAuthConfig defines the config for BasicAuthWithConfig middleware.

func (BasicAuthConfig) ToMiddleware

func (config BasicAuthConfig) ToMiddleware() (echo.MiddlewareFunc, error)

ToMiddleware converts BasicAuthConfig to middleware or returns an error for invalid configuration

type BasicAuthValidator

type BasicAuthValidator func(c echo.Context, user string, password string) (bool, error)

BasicAuthValidator defines a function to validate BasicAuthWithConfig credentials.

type BeforeFunc

type BeforeFunc func(c echo.Context)

BeforeFunc defines a function which is executed just before the middleware.

type BodyDumpConfig

type BodyDumpConfig struct {
	// Skipper defines a function to skip middleware.
	Skipper Skipper

	// Handler receives request and response payload.
	// Required.
	Handler BodyDumpHandler
}

BodyDumpConfig defines the config for BodyDump middleware.

func (BodyDumpConfig) ToMiddleware

func (config BodyDumpConfig) ToMiddleware() (echo.MiddlewareFunc, error)

ToMiddleware converts BodyDumpConfig to middleware or returns an error for invalid configuration

type BodyDumpHandler

type BodyDumpHandler func(c echo.Context, reqBody []byte, resBody []byte)

BodyDumpHandler receives the request and response payload.

type BodyLimitConfig

type BodyLimitConfig struct {
	// Skipper defines a function to skip middleware.
	Skipper Skipper

	// LimitBytes is maximum allowed size in bytes for a request body
	LimitBytes int64
}

BodyLimitConfig defines the config for BodyLimitWithConfig middleware.

func (BodyLimitConfig) ToMiddleware

func (config BodyLimitConfig) ToMiddleware() (echo.MiddlewareFunc, error)

ToMiddleware converts BodyLimitConfig to middleware or returns an error for invalid configuration

type CORSConfig

type CORSConfig struct {
	// Skipper defines a function to skip middleware.
	Skipper Skipper

	// AllowOrigins determines the value of the Access-Control-Allow-Origin
	// response header.  This header defines a list of origins that may access the
	// resource.  The wildcard characters '*' and '?' are supported and are
	// converted to regex fragments '.*' and '.' accordingly.
	//
	// Security: use extreme caution when handling the origin, and carefully
	// validate any logic. Remember that attackers may register hostile domain names.
	// See https://blog.portswigger.net/2016/10/exploiting-cors-misconfigurations-for.html
	//
	// Optional. Default value []string{"*"}.
	//
	// See also: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin
	AllowOrigins []string

	// AllowOriginFunc is a custom function to validate the origin. It takes the
	// origin as an argument and returns true if allowed or false otherwise. If
	// an error is returned, it is returned by the handler. If this option is
	// set, AllowOrigins is ignored.
	//
	// Security: use extreme caution when handling the origin, and carefully
	// validate any logic. Remember that attackers may register hostile domain names.
	// See https://blog.portswigger.net/2016/10/exploiting-cors-misconfigurations-for.html
	//
	// Optional.
	AllowOriginFunc func(origin string) (bool, error)

	// AllowMethods determines the value of the Access-Control-Allow-Methods
	// response header.  This header specified the list of methods allowed when
	// accessing the resource.  This is used in response to a preflight request.
	//
	// Optional. Default value DefaultCORSConfig.AllowMethods.
	// If `allowMethods` is left empty, this middleware will fill for preflight
	// request `Access-Control-Allow-Methods` header value
	// from `Allow` header that echo.Router set into context.
	//
	// See also: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Methods
	AllowMethods []string

	// AllowHeaders determines the value of the Access-Control-Allow-Headers
	// response header.  This header is used in response to a preflight request to
	// indicate which HTTP headers can be used when making the actual request.
	//
	// Optional. Default value []string{}.
	//
	// See also: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers
	AllowHeaders []string

	// AllowCredentials determines the value of the
	// Access-Control-Allow-Credentials response header.  This header indicates
	// whether or not the response to the request can be exposed when the
	// credentials mode (Request.credentials) is true. When used as part of a
	// response to a preflight request, this indicates whether or not the actual
	// request can be made using credentials.  See also
	// [MDN: Access-Control-Allow-Credentials].
	//
	// Optional. Default value false, in which case the header is not set.
	//
	// Security: avoid using `AllowCredentials = true` with `AllowOrigins = *`.
	// See "Exploiting CORS misconfigurations for Bitcoins and bounties",
	// https://blog.portswigger.net/2016/10/exploiting-cors-misconfigurations-for.html
	//
	// See also: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials
	AllowCredentials bool

	// UnsafeWildcardOriginWithAllowCredentials UNSAFE/INSECURE: allows wildcard '*' origin to be used with AllowCredentials
	// flag. In that case we consider any origin allowed and send it back to the client with `Access-Control-Allow-Origin` header.
	//
	// This is INSECURE and potentially leads to [cross-origin](https://portswigger.net/research/exploiting-cors-misconfigurations-for-bitcoins-and-bounties)
	// attacks. See: https://github.com/labstack/echo/issues/2400 for discussion on the subject.
	//
	// Optional. Default value is false.
	UnsafeWildcardOriginWithAllowCredentials bool

	// ExposeHeaders determines the value of Access-Control-Expose-Headers, which
	// defines a list of headers that clients are allowed to access.
	//
	// Optional. Default value []string{}, in which case the header is not set.
	//
	// See also: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Header
	ExposeHeaders []string

	// MaxAge determines the value of the Access-Control-Max-Age response header.
	// This header indicates how long (in seconds) the results of a preflight
	// request can be cached.
	//
	// Optional. Default value 0.  The header is set only if MaxAge > 0.
	//
	// See also: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Max-Age
	MaxAge int
}

CORSConfig defines the config for CORS middleware.

func (CORSConfig) ToMiddleware

func (config CORSConfig) ToMiddleware() (echo.MiddlewareFunc, error)

ToMiddleware converts CORSConfig to middleware or returns an error for invalid configuration

type CSRFConfig

type CSRFConfig struct {
	// Skipper defines a function to skip middleware.
	Skipper Skipper

	// TokenLength is the length of the generated token.
	TokenLength uint8

	// TokenLookup is a string in the form of "<source>:<name>" or "<source>:<name>,<source>:<name>" that is used
	// to extract token from the request.
	// Optional. Default value "header:X-CSRF-Token".
	// Possible values:
	// - "header:<name>" or "header:<name>:<cut-prefix>"
	// - "query:<name>"
	// - "form:<name>"
	// Multiple sources example:
	// - "header:X-CSRF-Token,query:csrf"
	TokenLookup string `yaml:"token_lookup"`

	// Generator defines a function to generate token.
	// Optional. Defaults tp randomString(TokenLength).
	Generator func() string

	// Context key to store generated CSRF token into context.
	// Optional. Default value "csrf".
	ContextKey string

	// Name of the CSRF cookie. This cookie will store CSRF token.
	// Optional. Default value "csrf".
	CookieName string

	// Domain of the CSRF cookie.
	// Optional. Default value none.
	CookieDomain string

	// Path of the CSRF cookie.
	// Optional. Default value none.
	CookiePath string

	// Max age (in seconds) of the CSRF cookie.
	// Optional. Default value 86400 (24hr).
	CookieMaxAge int

	// Indicates if CSRF cookie is secure.
	// Optional. Default value false.
	CookieSecure bool

	// Indicates if CSRF cookie is HTTP only.
	// Optional. Default value false.
	CookieHTTPOnly bool

	// Indicates SameSite mode of the CSRF cookie.
	// Optional. Default value SameSiteDefaultMode.
	CookieSameSite http.SameSite

	// ErrorHandler defines a function which is executed for returning custom errors.
	ErrorHandler func(c echo.Context, err error) error
}

CSRFConfig defines the config for CSRF middleware.

func (CSRFConfig) ToMiddleware

func (config CSRFConfig) ToMiddleware() (echo.MiddlewareFunc, error)

ToMiddleware converts CSRFConfig to middleware or returns an error for invalid configuration

type ContextTimeoutConfig

type ContextTimeoutConfig struct {
	// Skipper defines a function to skip middleware.
	Skipper Skipper

	// ErrorHandler is a function when error aries in middeware execution.
	ErrorHandler func(c echo.Context, err error) error

	// Timeout configures a timeout for the middleware
	Timeout time.Duration
}

ContextTimeoutConfig defines the config for ContextTimeout middleware.

func (ContextTimeoutConfig) ToMiddleware

func (config ContextTimeoutConfig) ToMiddleware() (echo.MiddlewareFunc, error)

ToMiddleware converts Config to middleware.

type DecompressConfig

type DecompressConfig struct {
	// Skipper defines a function to skip middleware.
	Skipper Skipper

	// GzipDecompressPool defines an interface to provide the sync.Pool used to create/store Gzip readers
	GzipDecompressPool Decompressor
}

DecompressConfig defines the config for Decompress middleware.

func (DecompressConfig) ToMiddleware

func (config DecompressConfig) ToMiddleware() (echo.MiddlewareFunc, error)

ToMiddleware converts DecompressConfig to middleware or returns an error for invalid configuration

type Decompressor

type Decompressor interface {
	// contains filtered or unexported methods
}

Decompressor is used to get the sync.Pool used by the middleware to get Gzip readers

type DefaultGzipDecompressPool

type DefaultGzipDecompressPool struct {
}

DefaultGzipDecompressPool is the default implementation of Decompressor interface

type Extractor

type Extractor func(c echo.Context) (string, error)

Extractor is used to extract data from echo.Context

type ExtractorSource

type ExtractorSource string

ExtractorSource is type to indicate source for extracted value

const (
	// ExtractorSourceHeader means value was extracted from request header
	ExtractorSourceHeader ExtractorSource = "header"
	// ExtractorSourceQuery means value was extracted from request query parameters
	ExtractorSourceQuery ExtractorSource = "query"
	// ExtractorSourcePathParam means value was extracted from route path parameters
	ExtractorSourcePathParam ExtractorSource = "param"
	// ExtractorSourceCookie means value was extracted from request cookies
	ExtractorSourceCookie ExtractorSource = "cookie"
	// ExtractorSourceForm means value was extracted from request form values
	ExtractorSourceForm ExtractorSource = "form"
)

type GzipConfig

type GzipConfig struct {
	// Skipper defines a function to skip middleware.
	Skipper Skipper

	// Gzip compression level.
	// Optional. Default value -1.
	Level int

	// Length threshold before gzip compression is applied.
	// Optional. Default value 0.
	//
	// Most of the time you will not need to change the default. Compressing
	// a short response might increase the transmitted data because of the
	// gzip format overhead. Compressing the response will also consume CPU
	// and time on the server and the client (for decompressing). Depending on
	// your use case such a threshold might be useful.
	//
	// See also:
	// https://webmasters.stackexchange.com/questions/31750/what-is-recommended-minimum-object-size-for-gzip-performance-benefits
	MinLength int
}

GzipConfig defines the config for Gzip middleware.

func (GzipConfig) ToMiddleware

func (config GzipConfig) ToMiddleware() (echo.MiddlewareFunc, error)

ToMiddleware converts GzipConfig to middleware or returns an error for invalid configuration

type KeyAuthConfig

type KeyAuthConfig struct {
	// Skipper defines a function to skip middleware.
	Skipper Skipper

	// KeyLookup is a string in the form of "<source>:<name>" or "<source>:<name>,<source>:<name>" that is used
	// to extract key from the request.
	// Optional. Default value "header:Authorization".
	// Possible values:
	// - "header:<name>" or "header:<name>:<cut-prefix>"
	// 			`<cut-prefix>` is argument value to cut/trim prefix of the extracted value. This is useful if header
	//			value has static prefix like `Authorization: <auth-scheme> <authorisation-parameters>` where part that we
	//			want to cut is `<auth-scheme> ` note the space at the end.
	//			In case of basic authentication `Authorization: Basic <credentials>` prefix we want to remove is `Basic `.
	// - "query:<name>"
	// - "form:<name>"
	// - "cookie:<name>"
	// Multiple sources example:
	// - "header:Authorization,header:X-Api-Key"
	KeyLookup string

	// Validator is a function to validate key.
	// Required.
	Validator KeyAuthValidator

	// ErrorHandler defines a function which is executed when all lookups have been done and none of them passed Validator
	// function. ErrorHandler is executed with last missing (ErrExtractionValueMissing) or an invalid key.
	// It may be used to define a custom error.
	//
	// Note: when error handler swallows the error (returns nil) middleware continues handler chain execution towards handler.
	// This is useful in cases when portion of your site/api is publicly accessible and has extra features for authorized users
	// In that case you can use ErrorHandler to set default public auth value to request and continue with handler chain.
	ErrorHandler KeyAuthErrorHandler

	// ContinueOnIgnoredError allows the next middleware/handler to be called when ErrorHandler decides to
	// ignore the error (by returning `nil`).
	// This is useful when parts of your site/api allow public access and some authorized routes provide extra functionality.
	// In that case you can use ErrorHandler to set a default public key auth value in the request context
	// and continue. Some logic down the remaining execution chain needs to check that (public) key auth value then.
	ContinueOnIgnoredError bool
}

KeyAuthConfig defines the config for KeyAuth middleware.

func (KeyAuthConfig) ToMiddleware

func (config KeyAuthConfig) ToMiddleware() (echo.MiddlewareFunc, error)

ToMiddleware converts KeyAuthConfig to middleware or returns an error for invalid configuration

type KeyAuthErrorHandler

type KeyAuthErrorHandler func(c echo.Context, err error) error

KeyAuthErrorHandler defines a function which is executed for an invalid key.

type KeyAuthValidator

type KeyAuthValidator func(c echo.Context, key string, source ExtractorSource) (bool, error)

KeyAuthValidator defines a function to validate KeyAuth credentials.

type LoggerConfig

type LoggerConfig struct {
	// Skipper defines a function to skip middleware.
	Skipper Skipper

	// Tags to construct the logger format.
	//
	// - time_unix
	// - time_unix_milli
	// - time_unix_micro
	// - time_unix_nano
	// - time_rfc3339
	// - time_rfc3339_nano
	// - time_custom
	// - id (Request ID)
	// - remote_ip
	// - uri
	// - host
	// - method
	// - path
	// - route
	// - protocol
	// - referer
	// - user_agent
	// - status
	// - error
	// - latency (In nanoseconds)
	// - latency_human (Human readable)
	// - bytes_in (Bytes received)
	// - bytes_out (Bytes sent)
	// - header:<NAME>
	// - query:<NAME>
	// - form:<NAME>
	// - custom (see CustomTagFunc field)
	//
	// Example "${remote_ip} ${status}"
	//
	// Optional. Default value DefaultLoggerConfig.Format.
	Format string

	// Optional. Default value DefaultLoggerConfig.CustomTimeFormat.
	CustomTimeFormat string

	// CustomTagFunc is function called for `${custom}` tag to output user implemented text by writing it to buf.
	// Make sure that outputted text creates valid JSON string with other logged tags.
	// Optional.
	CustomTagFunc func(c echo.Context, buf *bytes.Buffer) (int, error)

	// Output is a writer where logs in JSON format are written.
	// Optional. Default destination `echo.Logger.Infof()`
	Output io.Writer
	// contains filtered or unexported fields
}

LoggerConfig defines the config for Logger middleware.

func (LoggerConfig) ToMiddleware

func (config LoggerConfig) ToMiddleware() (echo.MiddlewareFunc, error)

ToMiddleware converts LoggerConfig to middleware or returns an error for invalid configuration

type MethodOverrideConfig

type MethodOverrideConfig struct {
	// Skipper defines a function to skip middleware.
	Skipper Skipper

	// Getter is a function that gets overridden method from the request.
	// Optional. Default values MethodFromHeader(echo.HeaderXHTTPMethodOverride).
	Getter MethodOverrideGetter
}

MethodOverrideConfig defines the config for MethodOverride middleware.

func (MethodOverrideConfig) ToMiddleware

func (config MethodOverrideConfig) ToMiddleware() (echo.MiddlewareFunc, error)

ToMiddleware converts MethodOverrideConfig to middleware or returns an error for invalid configuration

type MethodOverrideGetter

type MethodOverrideGetter func(echo.Context) string

MethodOverrideGetter is a function that gets overridden method from the request

func MethodFromForm

func MethodFromForm(param string) MethodOverrideGetter

MethodFromForm is a `MethodOverrideGetter` that gets overridden method from the form parameter.

func MethodFromHeader

func MethodFromHeader(header string) MethodOverrideGetter

MethodFromHeader is a `MethodOverrideGetter` that gets overridden method from the request header.

func MethodFromQuery

func MethodFromQuery(param string) MethodOverrideGetter

MethodFromQuery is a `MethodOverrideGetter` that gets overridden method from the query parameter.

type ProxyBalancer

type ProxyBalancer interface {
	AddTarget(*ProxyTarget) bool
	RemoveTarget(string) bool
	Next(echo.Context) (*ProxyTarget, error)
}

ProxyBalancer defines an interface to implement a load balancing technique.

func NewRandomBalancer

func NewRandomBalancer(targets []*ProxyTarget) ProxyBalancer

NewRandomBalancer returns a random proxy balancer.

func NewRoundRobinBalancer

func NewRoundRobinBalancer(targets []*ProxyTarget) ProxyBalancer

NewRoundRobinBalancer returns a round-robin proxy balancer.

type ProxyConfig

type ProxyConfig struct {
	// Skipper defines a function to skip middleware.
	Skipper Skipper

	// Balancer defines a load balancing technique.
	// Required.
	Balancer ProxyBalancer

	// RetryCount defines the number of times a failed proxied request should be retried
	// using the next available ProxyTarget. Defaults to 0, meaning requests are never retried.
	RetryCount int

	// RetryFilter defines a function used to determine if a failed request to a
	// ProxyTarget should be retried. The RetryFilter will only be called when the number
	// of previous retries is less than RetryCount. If the function returns true, the
	// request will be retried. The provided error indicates the reason for the request
	// failure. When the ProxyTarget is unavailable, the error will be an instance of
	// echo.HTTPError with a Code of http.StatusBadGateway. In all other cases, the error
	// will indicate an internal error in the Proxy middleware. When a RetryFilter is not
	// specified, all requests that fail with http.StatusBadGateway will be retried. A custom
	// RetryFilter can be provided to only retry specific requests. Note that RetryFilter is
	// only called when the request to the target fails, or an internal error in the Proxy
	// middleware has occurred. Successful requests that return a non-200 response code cannot
	// be retried.
	RetryFilter func(c echo.Context, e error) bool

	// ErrorHandler defines a function which can be used to return custom errors from
	// the Proxy middleware. ErrorHandler is only invoked when there has been
	// either an internal error in the Proxy middleware or the ProxyTarget is
	// unavailable. Due to the way requests are proxied, ErrorHandler is not invoked
	// when a ProxyTarget returns a non-200 response. In these cases, the response
	// is already written so errors cannot be modified. ErrorHandler is only
	// invoked after all retry attempts have been exhausted.
	ErrorHandler func(c echo.Context, err error) error

	// Rewrite defines URL path rewrite rules. The values captured in asterisk can be
	// retrieved by index e.g. $1, $2 and so on.
	// Examples:
	// "/old":              "/new",
	// "/api/*":            "/$1",
	// "/js/*":             "/public/javascripts/$1",
	// "/users/*/orders/*": "/user/$1/order/$2",
	Rewrite map[string]string

	// RegexRewrite defines rewrite rules using regexp.Rexexp with captures
	// Every capture group in the values can be retrieved by index e.g. $1, $2 and so on.
	// Example:
	// "^/old/[0.9]+/":     "/new",
	// "^/api/.+?/(.*)":    "/v2/$1",
	RegexRewrite map[*regexp.Regexp]string

	// Context key to store selected ProxyTarget into context.
	// Optional. Default value "target".
	ContextKey string

	// To customize the transport to remote.
	// Examples: If custom TLS certificates are required.
	Transport http.RoundTripper

	// ModifyResponse defines function to modify response from ProxyTarget.
	ModifyResponse func(*http.Response) error
}

ProxyConfig defines the config for Proxy middleware.

func (ProxyConfig) ToMiddleware

func (config ProxyConfig) ToMiddleware() (echo.MiddlewareFunc, error)

ToMiddleware converts ProxyConfig to middleware or returns an error for invalid configuration

type ProxyTarget

type ProxyTarget struct {
	Name string
	URL  *url.URL
	Meta echo.Map
}

ProxyTarget defines the upstream target.

type RateLimiterConfig

type RateLimiterConfig struct {
	Skipper    Skipper
	BeforeFunc BeforeFunc
	// IdentifierExtractor uses echo.Context to extract the identifier for a visitor
	IdentifierExtractor Extractor
	// Store defines a store for the rate limiter
	Store RateLimiterStore
	// ErrorHandler provides a handler to be called when IdentifierExtractor returns an error
	ErrorHandler func(c echo.Context, err error) error
	// DenyHandler provides a handler to be called when RateLimiter denies access
	DenyHandler func(c echo.Context, identifier string, err error) error
}

RateLimiterConfig defines the configuration for the rate limiter

func (RateLimiterConfig) ToMiddleware

func (config RateLimiterConfig) ToMiddleware() (echo.MiddlewareFunc, error)

ToMiddleware converts RateLimiterConfig to middleware or returns an error for invalid configuration

type RateLimiterMemoryStore

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

RateLimiterMemoryStore is the built-in store implementation for RateLimiter

func NewRateLimiterMemoryStore

func NewRateLimiterMemoryStore(rateLimit float64) (store *RateLimiterMemoryStore)

NewRateLimiterMemoryStore returns an instance of RateLimiterMemoryStore with the provided rate (as req/s). for more info check out Limiter docs - https://pkg.go.dev/golang.org/x/time/rate#Limit.

Burst and ExpiresIn will be set to default values.

Note that if the provided rate is a float number and Burst is zero, Burst will be treated as the rounded down value of the rate.

Example (with 20 requests/sec):

limiterStore := middleware.NewRateLimiterMemoryStore(20)

func NewRateLimiterMemoryStoreWithConfig

func NewRateLimiterMemoryStoreWithConfig(config RateLimiterMemoryStoreConfig) (store *RateLimiterMemoryStore)

NewRateLimiterMemoryStoreWithConfig returns an instance of RateLimiterMemoryStore with the provided configuration. Rate must be provided. Burst will be set to the rounded down value of the configured rate if not provided or set to 0.

The build-in memory store is usually capable for modest loads. For higher loads other store implementations should be considered.

Characteristics: * Concurrency above 100 parallel requests may causes measurable lock contention * A high number of different IP addresses (above 16000) may be impacted by the internally used Go map * A high number of requests from a single IP address may cause lock contention

Example:

limiterStore := middleware.NewRateLimiterMemoryStoreWithConfig(
	middleware.RateLimiterMemoryStoreConfig{Rate: 50, Burst: 200, ExpiresIn: 5 * time.Minute},
)

func (*RateLimiterMemoryStore) Allow

func (store *RateLimiterMemoryStore) Allow(identifier string) (bool, error)

Allow implements RateLimiterStore.Allow

type RateLimiterMemoryStoreConfig

type RateLimiterMemoryStoreConfig struct {
	Rate      float64       // Rate of requests allowed to pass as req/s. For more info check out Limiter docs - https://pkg.go.dev/golang.org/x/time/rate#Limit.
	Burst     int           // Burst is maximum number of requests to pass at the same moment. It additionally allows a number of requests to pass when rate limit is reached.
	ExpiresIn time.Duration // ExpiresIn is the duration after that a rate limiter is cleaned up
}

RateLimiterMemoryStoreConfig represents configuration for RateLimiterMemoryStore

type RateLimiterStore

type RateLimiterStore interface {
	Allow(identifier string) (bool, error)
}

RateLimiterStore is the interface to be implemented by custom stores.

type RecoverConfig

type RecoverConfig struct {
	// Skipper defines a function to skip middleware.
	Skipper Skipper

	// Size of the stack to be printed.
	// Optional. Default value 4KB.
	StackSize int

	// DisableStackAll disables formatting stack traces of all other goroutines
	// into buffer after the trace for the current goroutine.
	// Optional. Default value false.
	DisableStackAll bool

	// DisablePrintStack disables printing stack trace.
	// Optional. Default value as false.
	DisablePrintStack bool
}

RecoverConfig defines the config for Recover middleware.

func (RecoverConfig) ToMiddleware

func (config RecoverConfig) ToMiddleware() (echo.MiddlewareFunc, error)

ToMiddleware converts RecoverConfig to middleware or returns an error for invalid configuration

type RedirectConfig

type RedirectConfig struct {
	// Skipper defines a function to skip middleware.
	Skipper

	// Status code to be used when redirecting the request.
	// Optional. Default value http.StatusMovedPermanently.
	Code int
	// contains filtered or unexported fields
}

RedirectConfig defines the config for Redirect middleware.

func (RedirectConfig) ToMiddleware

func (config RedirectConfig) ToMiddleware() (echo.MiddlewareFunc, error)

ToMiddleware converts RedirectConfig to middleware or returns an error for invalid configuration

type RemoveTrailingSlashConfig

type RemoveTrailingSlashConfig struct {
	// Skipper defines a function to skip middleware.
	Skipper Skipper

	// Status code to be used when redirecting the request.
	// Optional, but when provided the request is redirected using this code.
	RedirectCode int
}

RemoveTrailingSlashConfig is the middleware config for removing trailing slash from the request.

func (RemoveTrailingSlashConfig) ToMiddleware

func (config RemoveTrailingSlashConfig) ToMiddleware() (echo.MiddlewareFunc, error)

ToMiddleware converts RemoveTrailingSlashConfig to middleware or returns an error for invalid configuration

type RequestIDConfig

type RequestIDConfig struct {
	// Skipper defines a function to skip middleware.
	Skipper Skipper

	// Generator defines a function to generate an ID.
	// Optional. Default value random.String(32).
	Generator func() string

	// RequestIDHandler defines a function which is executed for a request id.
	RequestIDHandler func(c echo.Context, requestID string)

	// TargetHeader defines what header to look for to populate the id
	TargetHeader string
}

RequestIDConfig defines the config for RequestID middleware.

func (RequestIDConfig) ToMiddleware

func (config RequestIDConfig) ToMiddleware() (echo.MiddlewareFunc, error)

ToMiddleware converts RequestIDConfig to middleware or returns an error for invalid configuration

type RequestLoggerConfig

type RequestLoggerConfig struct {
	// Skipper defines a function to skip middleware.
	Skipper Skipper

	// BeforeNextFunc defines a function that is called before next middleware or handler is called in chain.
	BeforeNextFunc func(c echo.Context)
	// LogValuesFunc defines a function that is called with values extracted by logger from request/response.
	// Mandatory.
	LogValuesFunc func(c echo.Context, v RequestLoggerValues) error

	// HandleError instructs logger to call global error handler when next middleware/handler returns an error.
	// This is useful when you have custom error handler that can decide to use different status codes.
	//
	// A side-effect of calling global error handler is that now Response has been committed and sent to the client
	// and middlewares up in chain can not change Response status code or response body.
	HandleError bool

	// LogLatency instructs logger to record duration it took to execute rest of the handler chain (next(c) call).
	LogLatency bool
	// LogProtocol instructs logger to extract request protocol (i.e. `HTTP/1.1` or `HTTP/2`)
	LogProtocol bool
	// LogRemoteIP instructs logger to extract request remote IP. See `echo.Context.RealIP()` for implementation details.
	LogRemoteIP bool
	// LogHost instructs logger to extract request host value (i.e. `example.com`)
	LogHost bool
	// LogMethod instructs logger to extract request method value (i.e. `GET` etc)
	LogMethod bool
	// LogURI instructs logger to extract request URI (i.e. `/list?lang=en&page=1`)
	LogURI bool
	// LogURIPath instructs logger to extract request URI path part (i.e. `/list`)
	LogURIPath bool
	// LogRoutePath instructs logger to extract route path part to which request was matched to (i.e. `/user/:id`)
	LogRoutePath bool
	// LogRequestID instructs logger to extract request ID from request `X-Request-ID` header or response if request did not have value.
	LogRequestID bool
	// LogReferer instructs logger to extract request referer values.
	LogReferer bool
	// LogUserAgent instructs logger to extract request user agent values.
	LogUserAgent bool
	// LogStatus instructs logger to extract response status code. If handler chain returns an echo.HTTPError,
	// the status code is extracted from the echo.HTTPError returned
	LogStatus bool
	// LogError instructs logger to extract error returned from executed handler chain.
	LogError bool
	// LogContentLength instructs logger to extract content length header value. Note: this value could be different from
	// actual request body size as it could be spoofed etc.
	LogContentLength bool
	// LogResponseSize instructs logger to extract response content length value. Note: when used with Gzip middleware
	// this value may not be always correct.
	LogResponseSize bool
	// LogHeaders instructs logger to extract given list of headers from request. Note: request can contain more than
	// one header with same value so slice of values is been logger for each given header.
	//
	// Note: header values are converted to canonical form with http.CanonicalHeaderKey as this how request parser converts header
	// names to. For example, the canonical key for "accept-encoding" is "Accept-Encoding".
	LogHeaders []string
	// LogQueryParams instructs logger to extract given list of query parameters from request URI. Note: request can
	// contain more than one query parameter with same name so slice of values is been logger for each given query param name.
	LogQueryParams []string
	// LogFormValues instructs logger to extract given list of form values from request body+URI. Note: request can
	// contain more than one form value with same name so slice of values is been logger for each given form value name.
	LogFormValues []string
	// contains filtered or unexported fields
}

RequestLoggerConfig is configuration for Request Logger middleware.

func (RequestLoggerConfig) ToMiddleware

func (config RequestLoggerConfig) ToMiddleware() (echo.MiddlewareFunc, error)

ToMiddleware converts RequestLoggerConfig into middleware or returns an error for invalid configuration.

type RequestLoggerValues

type RequestLoggerValues struct {
	// StartTime is time recorded before next middleware/handler is executed.
	StartTime time.Time
	// Latency is duration it took to execute rest of the handler chain (next(c) call).
	Latency time.Duration
	// Protocol is request protocol (i.e. `HTTP/1.1` or `HTTP/2`)
	Protocol string
	// RemoteIP is request remote IP. See `echo.Context.RealIP()` for implementation details.
	RemoteIP string
	// Host is request host value (i.e. `example.com`)
	Host string
	// Method is request method value (i.e. `GET` etc)
	Method string
	// URI is request URI (i.e. `/list?lang=en&page=1`)
	URI string
	// URIPath is request URI path part (i.e. `/list`)
	URIPath string
	// RoutePath is route path part to which request was matched to (i.e. `/user/:id`)
	RoutePath string
	// RequestID is request ID from request `X-Request-ID` header or response if request did not have value.
	RequestID string
	// Referer is request referer values.
	Referer string
	// UserAgent is request user agent values.
	UserAgent string
	// Status is response status code. Then handler returns an echo.HTTPError then code from there.
	Status int
	// Error is error returned from executed handler chain.
	Error error
	// ContentLength is content length header value. Note: this value could be different from actual request body size
	// as it could be spoofed etc.
	ContentLength string
	// ResponseSize is response content length value. Note: when used with Gzip middleware this value may not be always correct.
	ResponseSize int64
	// Headers are list of headers from request. Note: request can contain more than one header with same value so slice
	// of values is what will be returned/logged for each given header.
	// Note: header values are converted to canonical form with http.CanonicalHeaderKey as this how request parser converts header
	// names to. For example, the canonical key for "accept-encoding" is "Accept-Encoding".
	Headers map[string][]string
	// QueryParams are list of query parameters from request URI. Note: request can contain more than one query parameter
	// with same name so slice of values is what will be returned/logged for each given query param name.
	QueryParams map[string][]string
	// FormValues are list of form values from request body+URI. Note: request can contain more than one form value with
	// same name so slice of values is what will be returned/logged for each given form value name.
	FormValues map[string][]string
}

RequestLoggerValues contains extracted values from logger.

type RewriteConfig

type RewriteConfig struct {
	// Skipper defines a function to skip middleware.
	Skipper Skipper

	// Rules defines the URL path rewrite rules. The values captured in asterisk can be
	// retrieved by index e.g. $1, $2 and so on.
	// Example:
	// "/old":              "/new",
	// "/api/*":            "/$1",
	// "/js/*":             "/public/javascripts/$1",
	// "/users/*/orders/*": "/user/$1/order/$2",
	// Required.
	Rules map[string]string

	// RegexRules defines the URL path rewrite rules using regexp.Rexexp with captures
	// Every capture group in the values can be retrieved by index e.g. $1, $2 and so on.
	// Example:
	// "^/old/[0.9]+/":     "/new",
	// "^/api/.+?/(.*)":     "/v2/$1",
	RegexRules map[*regexp.Regexp]string
}

RewriteConfig defines the config for Rewrite middleware.

func (RewriteConfig) ToMiddleware

func (config RewriteConfig) ToMiddleware() (echo.MiddlewareFunc, error)

ToMiddleware converts RewriteConfig to middleware or returns an error for invalid configuration

type SecureConfig

type SecureConfig struct {
	// Skipper defines a function to skip middleware.
	Skipper Skipper

	// XSSProtection provides protection against cross-site scripting attack (XSS)
	// by setting the `X-XSS-Protection` header.
	// Optional. Default value "1; mode=block".
	XSSProtection string

	// ContentTypeNosniff provides protection against overriding Content-Type
	// header by setting the `X-Content-Type-Options` header.
	// Optional. Default value "nosniff".
	ContentTypeNosniff string

	// XFrameOptions can be used to indicate whether or not a browser should
	// be allowed to render a page in a <frame>, <iframe> or <object> .
	// Sites can use this to avoid clickjacking attacks, by ensuring that their
	// content is not embedded into other sites.provides protection against
	// clickjacking.
	// Optional. Default value "SAMEORIGIN".
	// Possible values:
	// - "SAMEORIGIN" - The page can only be displayed in a frame on the same origin as the page itself.
	// - "DENY" - The page cannot be displayed in a frame, regardless of the site attempting to do so.
	// - "ALLOW-FROM uri" - The page can only be displayed in a frame on the specified origin.
	XFrameOptions string

	// HSTSMaxAge sets the `Strict-Transport-Security` header to indicate how
	// long (in seconds) browsers should remember that this site is only to
	// be accessed using HTTPS. This reduces your exposure to some SSL-stripping
	// man-in-the-middle (MITM) attacks.
	// Optional. Default value 0.
	HSTSMaxAge int

	// HSTSExcludeSubdomains won't include subdomains tag in the `Strict Transport Security`
	// header, excluding all subdomains from security policy. It has no effect
	// unless HSTSMaxAge is set to a non-zero value.
	// Optional. Default value false.
	HSTSExcludeSubdomains bool

	// ContentSecurityPolicy sets the `Content-Security-Policy` header providing
	// security against cross-site scripting (XSS), clickjacking and other code
	// injection attacks resulting from execution of malicious content in the
	// trusted web page context.
	// Optional. Default value "".
	ContentSecurityPolicy string

	// CSPReportOnly would use the `Content-Security-Policy-Report-Only` header instead
	// of the `Content-Security-Policy` header. This allows iterative updates of the
	// content security policy by only reporting the violations that would
	// have occurred instead of blocking the resource.
	// Optional. Default value false.
	CSPReportOnly bool

	// HSTSPreloadEnabled will add the preload tag in the `Strict Transport Security`
	// header, which enables the domain to be included in the HSTS preload list
	// maintained by Chrome (and used by Firefox and Safari): https://hstspreload.org/
	// Optional.  Default value false.
	HSTSPreloadEnabled bool

	// ReferrerPolicy sets the `Referrer-Policy` header providing security against
	// leaking potentially sensitive request paths to third parties.
	// Optional. Default value "".
	ReferrerPolicy string
}

SecureConfig defines the config for Secure middleware.

func (SecureConfig) ToMiddleware

func (config SecureConfig) ToMiddleware() (echo.MiddlewareFunc, error)

ToMiddleware converts SecureConfig to middleware or returns an error for invalid configuration

type Skipper

type Skipper func(c echo.Context) bool

Skipper defines a function to skip middleware. Returning true skips processing the middleware.

type StaticConfig

type StaticConfig struct {
	// Skipper defines a function to skip middleware.
	Skipper Skipper

	// Root directory from where the static content is served (relative to given Filesystem).
	// `Root: "."` means root folder from Filesystem.
	// Required.
	Root string

	// Filesystem provides access to the static content.
	// Optional. Defaults to echo.Filesystem (serves files from `.` folder where executable is started)
	Filesystem fs.FS

	// Index file for serving a directory.
	// Optional. Default value "index.html".
	Index string

	// Enable HTML5 mode by forwarding all not-found requests to root so that
	// SPA (single-page application) can handle the routing.
	// Optional. Default value false.
	HTML5 bool

	// Enable directory browsing.
	// Optional. Default value false.
	Browse bool

	// Enable ignoring of the base of the URL path.
	// Example: when assigning a static middleware to a non root path group,
	// the filesystem path is not doubled
	// Optional. Default value false.
	IgnoreBase bool

	// DisablePathUnescaping disables path parameter (param: *) unescaping. This is useful when router is set to unescape
	// all parameter and doing it again in this middleware would corrupt filename that is requested.
	DisablePathUnescaping bool

	// DirectoryListTemplate is template to list directory contents
	// Optional. Default to `directoryListHTMLTemplate` constant below.
	DirectoryListTemplate string
}

StaticConfig defines the config for Static middleware.

func (StaticConfig) ToMiddleware

func (config StaticConfig) ToMiddleware() (echo.MiddlewareFunc, error)

ToMiddleware converts StaticConfig to middleware or returns an error for invalid configuration

type ValueExtractorError

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

ValueExtractorError is error type when middleware extractor is unable to extract value from lookups

func (*ValueExtractorError) Error

func (e *ValueExtractorError) Error() string

Error returns errors text

type ValuesExtractor

type ValuesExtractor func(c echo.Context) ([]string, ExtractorSource, error)

ValuesExtractor defines a function for extracting values (keys/tokens) from the given context.

func CreateExtractors

func CreateExtractors(lookups string) ([]ValuesExtractor, error)

CreateExtractors creates ValuesExtractors from given lookups. Lookups is a string in the form of "<source>:<name>" or "<source>:<name>,<source>:<name>" that is used to extract key from the request. Possible values:

  • "header:<name>" or "header:<name>:<cut-prefix>" `<cut-prefix>` is argument value to cut/trim prefix of the extracted value. This is useful if header value has static prefix like `Authorization: <auth-scheme> <authorisation-parameters>` where part that we want to cut is `<auth-scheme> ` note the space at the end. In case of basic authentication `Authorization: Basic <credentials>` prefix we want to remove is `Basic `.
  • "query:<name>"
  • "param:<name>"
  • "form:<name>"
  • "cookie:<name>"

Multiple sources example: - "header:Authorization,header:X-Api-Key"

type Visitor

type Visitor struct {
	*rate.Limiter
	// contains filtered or unexported fields
}

Visitor signifies a unique user's limiter details

Jump to

Keyboard shortcuts

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