Documentation ¶
Index ¶
- Constants
- Variables
- func AddTrailingSlash() echo.MiddlewareFunc
- func AddTrailingSlashWithConfig(config TrailingSlashConfig) echo.MiddlewareFunc
- func BasicAuth(fn BasicAuthValidator) echo.MiddlewareFunc
- func BasicAuthWithConfig(config BasicAuthConfig) echo.MiddlewareFunc
- func BodyDump(handler BodyDumpHandler) echo.MiddlewareFunc
- func BodyDumpWithConfig(config BodyDumpConfig) echo.MiddlewareFunc
- func BodyFlush() echo.MiddlewareFunc
- func BodyFlushWithConfig(config BodyBufferConfig) echo.MiddlewareFunc
- func BodyLimit(limit string) echo.MiddlewareFunc
- func BodyLimitWithConfig(config BodyLimitConfig) echo.MiddlewareFunc
- func CORS() echo.MiddlewareFunc
- func CORSWithConfig(config CORSConfig) echo.MiddlewareFunc
- func CSRF() echo.MiddlewareFunc
- func CSRFWithConfig(config CSRFConfig) echo.MiddlewareFunc
- func Decompress() echo.MiddlewareFunc
- func DecompressWithConfig(config DecompressConfig) echo.MiddlewareFunc
- func DefaultSkipper(echo.Context) bool
- func GetPath(r *http.Request) string
- func Gzip() echo.MiddlewareFunc
- func GzipWithConfig(config GzipConfig) echo.MiddlewareFunc
- func HTTPSNonWWWRedirect() echo.MiddlewareFunc
- func HTTPSNonWWWRedirectWithConfig(config RedirectConfig) echo.MiddlewareFunc
- func HTTPSRedirect() echo.MiddlewareFunc
- func HTTPSRedirectWithConfig(config RedirectConfig) echo.MiddlewareFunc
- func HTTPSWWWRedirect() echo.MiddlewareFunc
- func HTTPSWWWRedirectWithConfig(config RedirectConfig) echo.MiddlewareFunc
- func JWT(key interface{}) echo.MiddlewareFunc
- func JWTWithConfig(config JWTConfig) echo.MiddlewareFunc
- func KeyAuth(fn KeyAuthValidator) echo.MiddlewareFunc
- func KeyAuthWithConfig(config KeyAuthConfig) echo.MiddlewareFunc
- func Logger() echo.MiddlewareFunc
- func LoggerWithConfig(config LoggerConfig) echo.MiddlewareFunc
- func MethodOverride() echo.MiddlewareFunc
- func MethodOverrideWithConfig(config MethodOverrideConfig) echo.MiddlewareFunc
- func NonWWWRedirect() echo.MiddlewareFunc
- func NonWWWRedirectWithConfig(config RedirectConfig) echo.MiddlewareFunc
- func Proxy(balancer ProxyBalancer) echo.MiddlewareFunc
- func ProxyWithConfig(config ProxyConfig) echo.MiddlewareFunc
- func RateLimiter(store RateLimiterStore) echo.MiddlewareFunc
- func RateLimiterWithConfig(config RateLimiterConfig) echo.MiddlewareFunc
- func Recover() echo.MiddlewareFunc
- func RecoverWithConfig(config RecoverConfig) echo.MiddlewareFunc
- func RemoveTrailingSlash() echo.MiddlewareFunc
- func RemoveTrailingSlashWithConfig(config TrailingSlashConfig) echo.MiddlewareFunc
- func RequestID() echo.MiddlewareFunc
- func RequestIDWithConfig(config RequestIDConfig) echo.MiddlewareFunc
- func RequestLoggerWithConfig(config RequestLoggerConfig) echo.MiddlewareFunc
- func Rewrite(rules map[string]string) echo.MiddlewareFunc
- func RewriteWithConfig(config RewriteConfig) echo.MiddlewareFunc
- func Secure() echo.MiddlewareFunc
- func SecureWithConfig(config SecureConfig) echo.MiddlewareFunc
- func Static(root string) echo.MiddlewareFunc
- func StaticWithConfig(config StaticConfig) echo.MiddlewareFunc
- func Timeout() echo.MiddlewareFunc
- func TimeoutWithConfig(config TimeoutConfig) echo.MiddlewareFunc
- func WWWRedirect() echo.MiddlewareFunc
- func WWWRedirectWithConfig(config RedirectConfig) echo.MiddlewareFunc
- type BasicAuthConfig
- type BasicAuthValidator
- type BeforeFunc
- type BodyBufferConfig
- type BodyDumpConfig
- type BodyDumpHandler
- type BodyLimitConfig
- type CORSConfig
- type CSRFConfig
- type CSRFErrorHandler
- type DecompressConfig
- type Decompressor
- type DefaultGzipDecompressPool
- type ErrKeyAuthMissing
- type Extractor
- type GzipConfig
- type JWTConfig
- type JWTErrorHandler
- type JWTErrorHandlerWithContext
- type JWTSuccessHandler
- type KeyAuthConfig
- type KeyAuthErrorHandler
- type KeyAuthValidator
- type LogErrorFunc
- type LoggerConfig
- type MethodOverrideConfig
- type MethodOverrideGetter
- type ProxyBalancer
- type ProxyConfig
- type ProxyTarget
- type RateLimiterConfig
- type RateLimiterMemoryStore
- type RateLimiterMemoryStoreConfig
- type RateLimiterStore
- type RecoverConfig
- type RedirectConfig
- type RequestIDConfig
- type RequestLoggerConfig
- type RequestLoggerValues
- type ResponseRecorder
- func (rb *ResponseRecorder) Flush()
- func (rb *ResponseRecorder) Header() http.Header
- func (rb *ResponseRecorder) Unwrap() http.ResponseWriter
- func (rb *ResponseRecorder) Write(buf []byte) (int, error)
- func (rb *ResponseRecorder) WriteHeader(code int)
- func (rb *ResponseRecorder) WriteString(str string) (int, error)
- type RewriteConfig
- type Route
- type Router
- func (r *Router) Add(method, path string, handler echo.HandlerFunc, ...) *Route
- func (r *Router) Any(path string, h echo.HandlerFunc, middleware ...echo.MiddlewareFunc) []*Route
- func (r *Router) CONNECT(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *Route
- func (r *Router) DELETE(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *Route
- func (r *Router) GET(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *Route
- func (r *Router) HEAD(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *Route
- func (r *Router) Match(methods []string, path string, h echo.HandlerFunc, ...) []*Route
- func (r *Router) OPTIONS(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *Route
- func (r *Router) PATCH(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *Route
- func (r *Router) POST(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *Route
- func (r *Router) PUT(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *Route
- func (r *Router) Remove(method, path string) error
- func (r *Router) Reverse(name string, params ...interface{}) string
- func (r *Router) Routes(next echo.HandlerFunc) echo.HandlerFunc
- func (r *Router) TRACE(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *Route
- func (r *Router) URI(handler echo.HandlerFunc, params ...interface{}) string
- func (r *Router) URL(h echo.HandlerFunc, params ...interface{}) string
- type SecureConfig
- type Skipper
- type StaticConfig
- type TimeoutConfig
- type TrailingSlashConfig
- type ValuesExtractor
- type Visitor
Constants ¶
const (
AlgorithmHS256 = "HS256"
)
Algorithms
const GZIPEncoding string = "gzip"
GZIPEncoding content-encoding header if set to "gzip", decompress body contents.
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 ¶
var ( ErrJWTMissing = echo.NewHTTPError(http.StatusBadRequest, "missing or malformed jwt") ErrJWTInvalid = echo.NewHTTPError(http.StatusUnauthorized, "invalid or expired jwt") )
Errors
var ( // ErrRateLimitExceeded denotes an error raised when rate limit is exceeded ErrRateLimitExceeded = echo.NewHTTPError(http.StatusTooManyRequests, "rate limit exceeded") // ErrExtractorError denotes an error raised when extractor function is unsuccessful ErrExtractorError = echo.NewHTTPError(http.StatusForbidden, "error while extracting identifier") )
errors
var ( MethodNotAllowedMiddleware = func(next echo.HandlerFunc) echo.HandlerFunc { return func(c echo.Context) error { routerAllowMethods, ok := c.Get(echo.ContextKeyHeaderAllow).(string) if ok && routerAllowMethods != "" { c.Response().Header().Set(echo.HeaderAllow, routerAllowMethods) } return echo.ErrMethodNotAllowed } } NotFoundMiddleware = func(next echo.HandlerFunc) echo.HandlerFunc { return func(c echo.Context) error { err := next(c) if err != nil { return err } if c.Response().Status == 0 { return echo.NotFoundHandler(c) } return nil } } )
Error handlers
var ( // DefaultBasicAuthConfig is the default BasicAuth middleware config. DefaultBasicAuthConfig = BasicAuthConfig{ Skipper: DefaultSkipper, Realm: defaultRealm, } )
var ( // DefaultBodyBufferConfig is the default BodyFlush middleware config. DefaultBodyBufferConfig = BodyBufferConfig{ Skipper: DefaultSkipper, } )
var ( // DefaultBodyDumpConfig is the default BodyDump middleware config. DefaultBodyDumpConfig = BodyDumpConfig{ Skipper: DefaultSkipper, } )
var ( // DefaultBodyLimitConfig is the default BodyLimit middleware config. DefaultBodyLimitConfig = BodyLimitConfig{ Skipper: DefaultSkipper, } )
var ( // DefaultCORSConfig is the default CORS middleware config. DefaultCORSConfig = CORSConfig{ Skipper: DefaultSkipper, AllowOrigins: []string{"*"}, AllowMethods: []string{http.MethodGet, http.MethodHead, http.MethodPut, http.MethodPatch, http.MethodPost, http.MethodDelete}, } )
var ( // DefaultCSRFConfig is the default CSRF middleware config. DefaultCSRFConfig = CSRFConfig{ Skipper: DefaultSkipper, TokenLength: 32, TokenLookup: "header:" + echo.HeaderXCSRFToken, ContextKey: "csrf", CookieName: "_csrf", CookieMaxAge: 86400, CookieSameSite: http.SameSiteDefaultMode, } )
var ( //DefaultDecompressConfig defines the config for decompress middleware DefaultDecompressConfig = DecompressConfig{ Skipper: DefaultSkipper, GzipDecompressPool: &DefaultGzipDecompressPool{}, } )
var ( // DefaultGzipConfig is the default Gzip middleware config. DefaultGzipConfig = GzipConfig{ Skipper: DefaultSkipper, Level: -1, } )
var ( // DefaultJWTConfig is the default JWT auth middleware config. DefaultJWTConfig = JWTConfig{ Skipper: DefaultSkipper, SigningMethod: AlgorithmHS256, ContextKey: "user", TokenLookup: "header:" + echo.HeaderAuthorization, TokenLookupFuncs: nil, AuthScheme: "Bearer", Claims: jwt.MapClaims{}, KeyFunc: nil, } )
var ( // DefaultKeyAuthConfig is the default KeyAuth middleware config. DefaultKeyAuthConfig = KeyAuthConfig{ Skipper: DefaultSkipper, KeyLookup: "header:" + echo.HeaderAuthorization, AuthScheme: "Bearer", } )
var ( // DefaultLoggerConfig is the default Logger middleware config. DefaultLoggerConfig = LoggerConfig{ Skipper: DefaultSkipper, Format: `{"time":"${time_rfc3339_nano}","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", // contains filtered or unexported fields } )
var ( // DefaultMethodOverrideConfig is the default MethodOverride middleware config. DefaultMethodOverrideConfig = MethodOverrideConfig{ Skipper: DefaultSkipper, Getter: MethodFromHeader(echo.HeaderXHTTPMethodOverride), } )
var ( // DefaultProxyConfig is the default Proxy middleware config. DefaultProxyConfig = ProxyConfig{ Skipper: DefaultSkipper, ContextKey: "target", } )
var DefaultRateLimiterConfig = RateLimiterConfig{ Skipper: DefaultSkipper, IdentifierExtractor: func(ctx echo.Context) (string, error) { id := ctx.RealIP() return id, nil }, ErrorHandler: func(context echo.Context, err error) error { return &echo.HTTPError{ Code: ErrExtractorError.Code, Message: ErrExtractorError.Message, Internal: err, } }, DenyHandler: func(context echo.Context, identifier string, err error) error { return &echo.HTTPError{ Code: ErrRateLimitExceeded.Code, Message: ErrRateLimitExceeded.Message, Internal: err, } }, }
DefaultRateLimiterConfig defines default values for RateLimiterConfig
var DefaultRateLimiterMemoryStoreConfig = RateLimiterMemoryStoreConfig{ ExpiresIn: 3 * time.Minute, }
DefaultRateLimiterMemoryStoreConfig provides default configuration values for RateLimiterMemoryStore
var ( // DefaultRecoverConfig is the default Recover middleware config. DefaultRecoverConfig = RecoverConfig{ Skipper: DefaultSkipper, StackSize: 4 << 10, DisableStackAll: false, DisablePrintStack: false, LogLevel: 0, LogErrorFunc: nil, } )
var DefaultRedirectConfig = RedirectConfig{ Skipper: DefaultSkipper, Code: http.StatusMovedPermanently, }
DefaultRedirectConfig is the default Redirect middleware config.
var ( // DefaultRequestIDConfig is the default RequestID middleware config. DefaultRequestIDConfig = RequestIDConfig{ Skipper: DefaultSkipper, Generator: generator, TargetHeader: echo.HeaderXRequestID, } )
var ( // DefaultRewriteConfig is the default Rewrite middleware config. DefaultRewriteConfig = RewriteConfig{ Skipper: DefaultSkipper, } )
var ( // DefaultSecureConfig is the default Secure middleware config. DefaultSecureConfig = SecureConfig{ Skipper: DefaultSkipper, XSSProtection: "1; mode=block", ContentTypeNosniff: "nosniff", XFrameOptions: "SAMEORIGIN", HSTSPreloadEnabled: false, } )
var ( // DefaultStaticConfig is the default Static middleware config. DefaultStaticConfig = StaticConfig{ Skipper: DefaultSkipper, Index: "index.html", } )
var ( // DefaultTimeoutConfig is the default Timeout middleware config. DefaultTimeoutConfig = TimeoutConfig{ Skipper: DefaultSkipper, Timeout: 0, ErrorMessage: "", } )
var ( // DefaultTrailingSlashConfig is the default TrailingSlash middleware config. DefaultTrailingSlashConfig = TrailingSlashConfig{ Skipper: DefaultSkipper, } )
var ErrCSRFInvalid = echo.NewHTTPError(http.StatusForbidden, "invalid csrf token")
ErrCSRFInvalid is returned when CSRF check fails
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 TrailingSlashConfig) echo.MiddlewareFunc
AddTrailingSlashWithConfig returns a AddTrailingSlash middleware with config. See `AddTrailingSlash()`.
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 BasicAuth middleware with config. See `BasicAuth()`.
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 BodyFlush ¶
func BodyFlush() echo.MiddlewareFunc
BodyFlush returns a BodyFlush middleware.
BodyFlush middleware buffer the request and response payload and flush next middlewares is done
func BodyFlushWithConfig ¶
func BodyFlushWithConfig(config BodyBufferConfig) echo.MiddlewareFunc
BodyFlushWithConfig returns a BodyFlush middleware with config. See: `BodyFlush()`.
func BodyLimit ¶
func BodyLimit(limit string) 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. Limit can be specified as `4x` or `4xB`, where x is one of the multiple from K, M, G, T or P.
func BodyLimitWithConfig ¶
func BodyLimitWithConfig(config BodyLimitConfig) echo.MiddlewareFunc
BodyLimitWithConfig returns a BodyLimit middleware with config. See: `BodyLimit()`.
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. 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. See `CSRF()`.
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 decompresses request body based if content encoding type is set to "gzip" with config
func DefaultSkipper ¶
func DefaultSkipper(echo.Context) bool
DefaultSkipper returns false which processes the middleware.
func GetPath ¶
GetPath returns RawPath, if it's empty returns Path from URL Difference between RawPath and Path is:
- Path is where request path is stored. Value is stored in decoded form: /%47%6f%2f becomes /Go/.
- RawPath is an optional field which only gets set if the default encoding is different from Path.
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 return Gzip middleware with config. See: `Gzip()`.
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 an HTTPSRedirect middleware with config. See `HTTPSNonWWWRedirect()`.
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 an HTTPSRedirect middleware with config. See `HTTPSRedirect()`.
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 an HTTPSRedirect middleware with config. See `HTTPSWWWRedirect()`.
func JWT ¶
func JWT(key interface{}) echo.MiddlewareFunc
JWT returns a JSON Web Token (JWT) auth middleware.
For valid token, it sets the user in context and calls next handler. For invalid token, it returns "401 - Unauthorized" error. For missing token, it returns "400 - Bad Request" error.
See: https://jwt.io/introduction See `JWTConfig.TokenLookup`
func JWTWithConfig ¶
func JWTWithConfig(config JWTConfig) echo.MiddlewareFunc
JWTWithConfig returns a JWT auth middleware with config. See: `JWT()`.
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 with config. See `KeyAuth()`.
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. See: `Logger()`.
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 MethodOverride middleware with config. See: `MethodOverride()`.
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 an HTTPSRedirect middleware with config. See `NonWWWRedirect()`.
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 with config. See: `Proxy()`
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 Recover middleware with config. See: `Recover()`.
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 TrailingSlashConfig) echo.MiddlewareFunc
RemoveTrailingSlashWithConfig returns a RemoveTrailingSlash middleware with config. See `RemoveTrailingSlash()`.
func RequestIDWithConfig ¶
func RequestIDWithConfig(config RequestIDConfig) echo.MiddlewareFunc
RequestIDWithConfig returns a X-Request-ID middleware with config.
func RequestLoggerWithConfig ¶
func RequestLoggerWithConfig(config RequestLoggerConfig) echo.MiddlewareFunc
RequestLoggerWithConfig returns a RequestLogger middleware with config.
func Rewrite ¶
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 with config. See: `Rewrite()`.
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. See: `Secure()`.
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 with config. See `Static()`.
func Timeout ¶
func Timeout() echo.MiddlewareFunc
Timeout returns a middleware which returns error (503 Service Unavailable error) to client immediately when handler call runs for longer than its time limit. NB: timeout does not stop handler execution.
func TimeoutWithConfig ¶
func TimeoutWithConfig(config TimeoutConfig) echo.MiddlewareFunc
TimeoutWithConfig returns a Timeout middleware with config 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 an HTTPSRedirect middleware with config. See `WWWRedirect()`.
Types ¶
type BasicAuthConfig ¶
type BasicAuthConfig struct { // Skipper defines a function to skip middleware. Skipper Skipper // Validator is a function to validate BasicAuth credentials. // Required. Validator BasicAuthValidator // Realm is a string to define realm attribute of BasicAuth. // Default value "Restricted". Realm string }
BasicAuthConfig defines the config for BasicAuth middleware.
type BasicAuthValidator ¶
BasicAuthValidator defines a function to validate BasicAuth credentials.
type BeforeFunc ¶
type BeforeFunc func(c echo.Context)
BeforeFunc defines a function which is executed just before the middleware.
type BodyBufferConfig ¶
type BodyBufferConfig struct { // Skipper defines a function to skip middleware. Skipper Skipper PreFlight bool }
BodyBufferConfig defines the config for BodyFlush 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.
type BodyDumpHandler ¶
BodyDumpHandler receives the request and response payload.
type BodyLimitConfig ¶
type BodyLimitConfig struct { // Skipper defines a function to skip middleware. Skipper Skipper // Maximum allowed size for a request body, it can be specified // as `4x` or `4xB`, where x is one of the multiple from K, M, G, T or P. Limit string `yaml:"limit"` // contains filtered or unexported fields }
BodyLimitConfig defines the config for BodyLimit middleware.
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 `yaml:"allow_origins"` // 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) `yaml:"allow_origin_func"` // 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 `yaml:"allow_methods"` // 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 `yaml:"allow_headers"` // 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 `yaml:"allow_credentials"` // 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 `yaml:"expose_headers"` // 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 `yaml:"max_age"` }
CORSConfig defines the config for CORS middleware.
type CSRFConfig ¶
type CSRFConfig struct { // Skipper defines a function to skip middleware. Skipper Skipper // TokenLength is the length of the generated token. TokenLength uint8 `yaml:"token_length"` // 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"` // Context key to store generated CSRF token into context. // Optional. Default value "csrf". ContextKey string `yaml:"context_key"` // Name of the CSRF cookie. This cookie will store CSRF token. // Optional. Default value "csrf". CookieName string `yaml:"cookie_name"` // Domain of the CSRF cookie. // Optional. Default value none. CookieDomain string `yaml:"cookie_domain"` // Path of the CSRF cookie. // Optional. Default value none. CookiePath string `yaml:"cookie_path"` // Max age (in seconds) of the CSRF cookie. // Optional. Default value 86400 (24hr). CookieMaxAge int `yaml:"cookie_max_age"` // Indicates if CSRF cookie is secure. // Optional. Default value false. CookieSecure bool `yaml:"cookie_secure"` // Indicates if CSRF cookie is HTTP only. // Optional. Default value false. CookieHTTPOnly bool `yaml:"cookie_http_only"` // Indicates SameSite mode of the CSRF cookie. // Optional. Default value SameSiteDefaultMode. CookieSameSite http.SameSite `yaml:"cookie_same_site"` // ErrorHandler defines a function which is executed for returning custom errors. ErrorHandler CSRFErrorHandler }
CSRFConfig defines the config for CSRF middleware.
type CSRFErrorHandler ¶
CSRFErrorHandler is a function which is executed for creating custom errors.
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.
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 ErrKeyAuthMissing ¶
type ErrKeyAuthMissing struct {
Err error
}
ErrKeyAuthMissing is error type when KeyAuth middleware is unable to extract value from lookups
func (*ErrKeyAuthMissing) Error ¶
func (e *ErrKeyAuthMissing) Error() string
Error returns errors text
type GzipConfig ¶
type GzipConfig struct { // Skipper defines a function to skip middleware. Skipper Skipper // Gzip compression level. // Optional. Default value -1. Level int `yaml:"level"` }
GzipConfig defines the config for Gzip middleware.
type JWTConfig ¶
type JWTConfig struct { // Skipper defines a function to skip middleware. Skipper Skipper // BeforeFunc defines a function which is executed just before the middleware. BeforeFunc BeforeFunc // SuccessHandler defines a function which is executed for a valid token before middleware chain continues with next // middleware or handler. SuccessHandler JWTSuccessHandler // ErrorHandler defines a function which is executed for an invalid token. // It may be used to define a custom JWT error. ErrorHandler JWTErrorHandler // ErrorHandlerWithContext is almost identical to ErrorHandler, but it's passed the current context. ErrorHandlerWithContext JWTErrorHandlerWithContext // ContinueOnIgnoredError allows the next middleware/handler to be called when ErrorHandlerWithContext 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 ErrorHandlerWithContext to set a default public JWT token value in the request context // and continue. Some logic down the remaining execution chain needs to check that (public) token value then. ContinueOnIgnoredError bool // Signing key to validate token. // This is one of the three options to provide a token validation key. // The order of precedence is a user-defined KeyFunc, SigningKeys and SigningKey. // Required if neither user-defined KeyFunc nor SigningKeys is provided. SigningKey interface{} // Map of signing keys to validate token with kid field usage. // This is one of the three options to provide a token validation key. // The order of precedence is a user-defined KeyFunc, SigningKeys and SigningKey. // Required if neither user-defined KeyFunc nor SigningKey is provided. SigningKeys map[string]interface{} // Signing method used to check the token's signing algorithm. // Optional. Default value HS256. SigningMethod string // Context key to store user information from the token into context. // Optional. Default value "user". ContextKey string // Claims are extendable claims data defining token content. Used by default ParseTokenFunc implementation. // Not used if custom ParseTokenFunc is set. // Optional. Default value jwt.MapClaims Claims jwt.Claims // 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: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 JWT tokens `Authorization: Bearer <token>` prefix we cut is `Bearer `. // If prefix is left empty the whole value is returned. // - "query:<name>" // - "param:<name>" // - "cookie:<name>" // - "form:<name>" // Multiple sources example: // - "header:Authorization,cookie:myowncookie" TokenLookup string // TokenLookupFuncs defines a list of user-defined functions that extract JWT token from the given context. // This is one of the two options to provide a token extractor. // The order of precedence is user-defined TokenLookupFuncs, and TokenLookup. // You can also provide both if you want. TokenLookupFuncs []ValuesExtractor // AuthScheme to be used in the Authorization header. // Optional. Default value "Bearer". AuthScheme string // KeyFunc defines a user-defined function that supplies the public key for a token validation. // The function shall take care of verifying the signing algorithm and selecting the proper key. // A user-defined KeyFunc can be useful if tokens are issued by an external party. // Used by default ParseTokenFunc implementation. // // When a user-defined KeyFunc is provided, SigningKey, SigningKeys, and SigningMethod are ignored. // This is one of the three options to provide a token validation key. // The order of precedence is a user-defined KeyFunc, SigningKeys and SigningKey. // Required if neither SigningKeys nor SigningKey is provided. // Not used if custom ParseTokenFunc is set. // Default to an internal implementation verifying the signing algorithm and selecting the proper key. KeyFunc jwt.Keyfunc // ParseTokenFunc defines a user-defined function that parses token from given auth. Returns an error when token // parsing fails or parsed token is invalid. // Defaults to implementation using `github.com/golang-jwt/jwt` as JWT implementation library ParseTokenFunc func(auth string, c echo.Context) (interface{}, error) }
JWTConfig defines the config for JWT middleware.
type JWTErrorHandler ¶
JWTErrorHandler defines a function which is executed for an invalid token.
type JWTErrorHandlerWithContext ¶
JWTErrorHandlerWithContext is almost identical to JWTErrorHandler, but it's passed the current context.
type JWTSuccessHandler ¶
type JWTSuccessHandler func(c echo.Context)
JWTSuccessHandler defines a function which is executed for a valid token.
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 // AuthScheme to be used in the Authorization header. // Optional. Default value "Bearer". AuthScheme string // Validator is a function to validate key. // Required. Validator KeyAuthValidator // ErrorHandler defines a function which is executed for an invalid key. // It may be used to define a custom error. 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.
type KeyAuthErrorHandler ¶
KeyAuthErrorHandler defines a function which is executed for an invalid key.
type KeyAuthValidator ¶
KeyAuthValidator defines a function to validate KeyAuth credentials.
type LogErrorFunc ¶
LogErrorFunc defines a function for custom logging in the middleware.
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 // - 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> // // Example "${remote_ip} ${status}" // // Optional. Default value DefaultLoggerConfig.Format. Format string `yaml:"format"` // Optional. Default value DefaultLoggerConfig.CustomTimeFormat. CustomTimeFormat string `yaml:"custom_time_format"` // Output is a writer where logs in JSON format are written. // Optional. Default value os.Stdout. Output io.Writer // contains filtered or unexported fields }
LoggerConfig defines the config for Logger middleware.
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.
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 }
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 // 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.
type ProxyTarget ¶
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(context echo.Context, err error) error // DenyHandler provides a handler to be called when RateLimiter denies access DenyHandler func(context echo.Context, identifier string, err error) error }
RateLimiterConfig defines the configuration for the rate limiter
type RateLimiterMemoryStore ¶
type RateLimiterMemoryStore struct {
// contains filtered or unexported fields
}
RateLimiterMemoryStore is the built-in store implementation for RateLimiter
func NewRateLimiterMemoryStore ¶
func NewRateLimiterMemoryStore(rate rate.Limit) (store *RateLimiterMemoryStore)
NewRateLimiterMemoryStore returns an instance of RateLimiterMemoryStore with the provided rate (as req/s). The provided rate less than 1 will be treated as zero. 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.
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 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}, )
type RateLimiterMemoryStoreConfig ¶
type RateLimiterMemoryStoreConfig struct { Rate rate.Limit // 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 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 { // Stores for the rate limiter have to implement the Allow method 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 `yaml:"stack_size"` // DisableStackAll disables formatting stack traces of all other goroutines // into buffer after the trace for the current goroutine. // Optional. Default value false. DisableStackAll bool `yaml:"disable_stack_all"` // DisablePrintStack disables printing stack trace. // Optional. Default value as false. DisablePrintStack bool `yaml:"disable_print_stack"` // LogLevel is log level to printing stack trace. // Optional. Default value 0 (Print). LogLevel log.Lvl // LogErrorFunc defines a function for custom logging in the middleware. // If it's set you don't need to provide LogLevel for config. LogErrorFunc LogErrorFunc }
RecoverConfig defines the config for Recover middleware.
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 `yaml:"code"` }
RedirectConfig defines the config for Redirect middleware.
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(echo.Context, string) // TargetHeader defines what header to look for to populate the id TargetHeader string }
RequestIDConfig defines the config for RequestID middleware.
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 // 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 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". 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 been logger 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 been logger for each given form value name. FormValues map[string][]string }
RequestLoggerValues contains extracted values from logger.
type ResponseRecorder ¶
type ResponseRecorder struct { // Code is the HTTP response code set by WriteHeader. // // Note that if a Handler never calls WriteHeader or Write, // this might end up being 0, rather than the implicit // http.StatusOK. To get the implicit value, use the Result // method. Code int // HeaderMap contains the headers explicitly set by the Handler. HeaderMap http.Header // Body is the buffer to which the Handler's Write calls are sent. // If nil, the Writes are silently discarded. Body *bytes.Buffer // Flushable is whether the Handler called Flush. Flushable bool Flushed bool Committed bool // contains filtered or unexported fields }
ResponseRecorder defines the buffered reposes.
func NewResponseBufferedWriter ¶
func NewResponseBufferedWriter(writer http.ResponseWriter) *ResponseRecorder
NewResponseBufferedWriter returns an initialized ResponseBuffere.
func (*ResponseRecorder) Flush ¶
func (rb *ResponseRecorder) Flush()
Flush implements http.Flusher. To test whether Flush was called, see rw.Flushed.
func (*ResponseRecorder) Header ¶
func (rb *ResponseRecorder) Header() http.Header
Header implements http.ResponseWriter. It returns the response headers to mutate within a handler. To test the headers that were written after a handler completes, use the Result method and see the returned Response value's Header.
func (*ResponseRecorder) Unwrap ¶
func (rb *ResponseRecorder) Unwrap() http.ResponseWriter
Unwrap return origin response writer
func (*ResponseRecorder) Write ¶
func (rb *ResponseRecorder) Write(buf []byte) (int, error)
Write implements http.ResponseWriter. The data in buf is written to rw.Body, if not nil.
func (*ResponseRecorder) WriteHeader ¶
func (rb *ResponseRecorder) WriteHeader(code int)
WriteHeader implements http.ResponseWriter.
func (*ResponseRecorder) WriteString ¶
func (rb *ResponseRecorder) WriteString(str string) (int, error)
WriteString implements io.StringWriter. The data in str is written to rw.Body, if not nil.
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 `yaml:"rules"` // 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 `yaml:"regex_rules"` }
RewriteConfig defines the config for Rewrite middleware.
type Route ¶
type Route struct { Method string `json:"method"` Path string `json:"path"` Name string `json:"name"` }
Route contains a handler and information for matching against requests.
type Router ¶
type Router struct {
// contains filtered or unexported fields
}
Router is the registry of all registered routes for an `Echo` instance for request matching and URL path parameter parsing.
func (*Router) Add ¶
func (r *Router) Add(method, path string, handler echo.HandlerFunc, middleware ...echo.MiddlewareFunc) *Route
Add registers a new route for method and path with matching handler.
func (*Router) Any ¶
Any registers a new route for all HTTP methods and path with matching handler in the router with optional route-level middleware.
func (*Router) CONNECT ¶
CONNECT registers a new CONNECT route for a path with matching handler in the router with optional route-level middleware.
func (*Router) DELETE ¶
DELETE registers a new DELETE route for a path with matching handler in the router with optional route-level middleware.
func (*Router) GET ¶
GET registers a new GET route for a path with matching handler in the router with optional route-level middleware.
func (*Router) HEAD ¶
HEAD registers a new HEAD route for a path with matching handler in the router with optional route-level middleware.
func (*Router) Match ¶
func (r *Router) Match(methods []string, path string, h echo.HandlerFunc, middleware ...echo.MiddlewareFunc) []*Route
Match registers a new route for multiple HTTP methods and path with matching handler in the router with optional route-level middleware.
func (*Router) OPTIONS ¶
OPTIONS registers a new OPTIONS route for a path with matching handler in the router with optional route-level middleware.
func (*Router) PATCH ¶
PATCH registers a new PATCH route for a path with matching handler in the router with optional route-level middleware.
func (*Router) POST ¶
POST registers a new POST route for a path with matching handler in the router with optional route-level middleware.
func (*Router) PUT ¶
PUT registers a new PUT route for a path with matching handler in the router with optional route-level middleware.
func (*Router) Routes ¶
func (r *Router) Routes(next echo.HandlerFunc) echo.HandlerFunc
Routes return echo handlerFunc
func (*Router) TRACE ¶
TRACE registers a new TRACE route for a path with matching handler in the router with optional route-level middleware.
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 `yaml:"xss_protection"` // ContentTypeNosniff provides protection against overriding Content-Type // header by setting the `X-Content-Type-Options` header. // Optional. Default value "nosniff". ContentTypeNosniff string `yaml:"content_type_nosniff"` // 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 `yaml:"x_frame_options"` // 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 `yaml:"hsts_max_age"` // 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 `yaml:"hsts_exclude_subdomains"` // 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 `yaml:"content_security_policy"` // 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 `yaml:"csp_report_only"` // 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 `yaml:"hsts_preload_enabled"` // ReferrerPolicy sets the `Referrer-Policy` header providing security against // leaking potentially sensitive request paths to third parties. // Optional. Default value "". ReferrerPolicy string `yaml:"referrer_policy"` }
SecureConfig defines the config for Secure middleware.
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. // Required. Root string `yaml:"root"` // Index file for serving a directory. // Optional. Default value "index.html". Index string `yaml:"index"` // 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 `yaml:"html5"` // Enable directory browsing. // Optional. Default value false. Browse bool `yaml:"browse"` // 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 `yaml:"ignoreBase"` // Filesystem provides access to the static content. // Optional. Defaults to http.Dir(config.Root) Filesystem http.FileSystem `yaml:"-"` }
StaticConfig defines the config for Static middleware.
type TimeoutConfig ¶
type TimeoutConfig struct { // Skipper defines a function to skip middleware. Skipper Skipper // ErrorMessage is written to response on timeout in addition to http.StatusServiceUnavailable (503) status code // It can be used to define a custom timeout error message ErrorMessage string // OnTimeoutRouteErrorHandler is an error handler that is executed for error that was returned from wrapped route after // request timeouted and we already had sent the error code (503) and message response to the client. // NB: do not write headers/body inside this handler. The response has already been sent to the client and response writer // will not accept anything no more. If you want to know what actual route middleware timeouted use `c.Path()` OnTimeoutRouteErrorHandler func(err error, c echo.Context) // Timeout configures a timeout for the middleware, defaults to 0 for no timeout // NOTE: when difference between timeout duration and handler execution time is almost the same (in range of 100microseconds) // the result of timeout does not seem to be reliable - could respond timeout, could respond handler output // difference over 500microseconds (0.5millisecond) response seems to be reliable Timeout time.Duration }
TimeoutConfig defines the config for Timeout middleware.
func (TimeoutConfig) ToMiddleware ¶
func (config TimeoutConfig) ToMiddleware() (echo.MiddlewareFunc, error)
ToMiddleware converts Config to middleware or returns an error for invalid configuration
type TrailingSlashConfig ¶
type TrailingSlashConfig 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 `yaml:"redirect_code"` }
TrailingSlashConfig defines the config for TrailingSlash middleware.
type ValuesExtractor ¶
ValuesExtractor defines a function for extracting values (keys/tokens) from the given context.
Source Files ¶
- basic_auth.go
- body_dump.go
- body_flush.go
- body_limit.go
- compress.go
- cors.go
- csrf.go
- decompress.go
- extractor.go
- jwt.go
- key_auth.go
- logger.go
- method_override.go
- middleware.go
- proxy.go
- rate_limiter.go
- recover.go
- redirect.go
- request_id.go
- request_logger.go
- rewrite.go
- router.go
- secure.go
- slash.go
- static.go
- timeout.go
- util.go