middleware

package
v2.0.1+incompatible Latest Latest
Warning

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

Go to latest
Published: Jun 11, 2016 License: MIT Imports: 27 Imported by: 0

Documentation

Index

Constants

View Source
const (
	AlgorithmHS256 = "HS256"
)

Algorithims

Variables

View Source
var (
	// DefaultCORSConfig is the default CORS middleware config.
	DefaultCORSConfig = CORSConfig{
		AllowOrigins: []string{"*"},
		AllowMethods: []string{echo.GET, echo.HEAD, echo.PUT, echo.PATCH, echo.POST, echo.DELETE},
	}
)
View Source
var (
	// DefaultCSRFConfig is the default CSRF middleware config.
	DefaultCSRFConfig = CSRFConfig{
		TokenLookup:   "header:" + echo.HeaderXCSRFToken,
		ContextKey:    "csrf",
		CookieName:    "csrf",
		CookieExpires: time.Now().Add(24 * time.Hour),
	}
)
View Source
var (
	// DefaultGzipConfig is the default gzip middleware config.
	DefaultGzipConfig = GzipConfig{
		Level: -1,
	}
)
View Source
var (
	// DefaultJWTConfig is the default JWT auth middleware config.
	DefaultJWTConfig = JWTConfig{
		SigningMethod: AlgorithmHS256,
		ContextKey:    "user",
		TokenLookup:   "header:" + echo.HeaderAuthorization,
	}
)
View Source
var (
	// DefaultLoggerConfig is the default logger middleware config.
	DefaultLoggerConfig = LoggerConfig{
		Format: `{"time":"${time_rfc3339}","remote_ip":"${remote_ip}",` +
			`"method":"${method}","uri":"${uri}","status":${status}, "latency":${latency},` +
			`"latency_human":"${latency_human}","rx_bytes":${rx_bytes},` +
			`"tx_bytes":${tx_bytes}}` + "\n",

		Output: os.Stdout,
		// contains filtered or unexported fields
	}
)
View Source
var (
	// DefaultMethodOverrideConfig is the default method override middleware config.
	DefaultMethodOverrideConfig = MethodOverrideConfig{
		Getter: MethodFromHeader(echo.HeaderXHTTPMethodOverride),
	}
)
View Source
var (
	// DefaultRecoverConfig is the default recover middleware config.
	DefaultRecoverConfig = RecoverConfig{
		StackSize:         4 << 10,
		DisableStackAll:   false,
		DisablePrintStack: false,
	}
)
View Source
var (
	// DefaultSecureConfig is the default secure middleware config.
	DefaultSecureConfig = SecureConfig{
		XSSProtection:      "1; mode=block",
		ContentTypeNosniff: "nosniff",
		XFrameOptions:      "SAMEORIGIN",
	}
)
View Source
var (
	// DefaultStaticConfig is the default static middleware config.
	DefaultStaticConfig = StaticConfig{
		Index: "index.html",
	}
)

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 from config. See `AddTrailingSlash()`.

func BasicAuth

BasicAuth returns an HTTP basic auth middleware.

For valid credentials it calls the next handler. For invalid credentials, it sends "401 - Unauthorized" response. For empty or invalid `Authorization` header, it sends "400 - Bad Request" response.

func BasicAuthWithConfig

func BasicAuthWithConfig(config BasicAuthConfig) echo.MiddlewareFunc

BasicAuthWithConfig returns an HTTP basic auth middleware from config. See `BasicAuth()`.

func BodyLimit

func BodyLimit(limit string) echo.MiddlewareFunc

BodyLimit returns a body limit 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 body limit 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 body limit middleware from config. See: `BodyLimit()`.

func CORS

func CORS() echo.MiddlewareFunc

CORS returns a Cross-Origin Resource Sharing (CORS) middleware. See: https://developer.mozilla.org/en/docs/Web/HTTP/Access_control_CORS

func CORSWithConfig

func CORSWithConfig(config CORSConfig) echo.MiddlewareFunc

CORSWithConfig returns a CORS middleware from config. See: `CORS()`.

func CSRF

func CSRF(secret []byte) 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 from config. See `CSRF()`.

func Gzip added in v0.0.13

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 from config. See: `Gzip()`.

func JWT

func JWT(key []byte) 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 sends "401 - Unauthorized" response. For empty or invalid `Authorization` header, it sends "400 - Bad Request".

See: https://jwt.io/introduction

func JWTWithConfig

func JWTWithConfig(config JWTConfig) echo.MiddlewareFunc

JWTWithConfig returns a JWT auth middleware from config. See: `JWT()`.

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 from config. See: `Logger()`.

func MethodOverride

func MethodOverride() echo.MiddlewareFunc

MethodOverride returns a method override 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 from config. See: `MethodOverride()`.

func Recover added in v0.0.13

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 from 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 from config. See `RemoveTrailingSlash()`.

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 from 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 from config. See `Static()`.

Types

type BasicAuthConfig

type BasicAuthConfig struct {
	// Validator is a function to validate basic auth credentials.
	Validator BasicAuthValidator
}

BasicAuthConfig defines the config for HTTP basic auth middleware.

type BasicAuthValidator

type BasicAuthValidator func(string, string) bool

BasicAuthValidator defines a function to validate basic auth credentials.

type BodyLimitConfig

type BodyLimitConfig struct {
	// 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 `json:"limit"`
	// contains filtered or unexported fields
}

BodyLimitConfig defines the config for body limit middleware.

type CORSConfig

type CORSConfig struct {
	// AllowOrigin defines a list of origins that may access the resource.
	// Optional. Default value []string{"*"}.
	AllowOrigins []string `json:"allow_origins"`

	// AllowMethods defines a list methods allowed when accessing the resource.
	// This is used in response to a preflight request.
	// Optional. Default value DefaultCORSConfig.AllowMethods.
	AllowMethods []string `json:"allow_methods"`

	// AllowHeaders defines a list of request headers that can be used when
	// making the actual request. This in response to a preflight request.
	// Optional. Default value []string{}.
	AllowHeaders []string `json:"allow_headers"`

	// AllowCredentials indicates whether or not the response to the request
	// can be exposed when the credentials flag 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.
	// Optional. Default value false.
	AllowCredentials bool `json:"allow_credentials"`

	// ExposeHeaders defines a whitelist headers that clients are allowed to
	// access.
	// Optional. Default value []string{}.
	ExposeHeaders []string `json:"expose_headers"`

	// MaxAge indicates how long (in seconds) the results of a preflight request
	// can be cached.
	// Optional. Default value 0.
	MaxAge int `json:"max_age"`
}

CORSConfig defines the config for CORS middleware.

type CSRFConfig

type CSRFConfig struct {
	// Key to create CSRF token.
	Secret []byte `json:"secret"`

	// TokenLookup is a string in the form of "<source>:<key>" that is used
	// to extract token from the request.
	// Optional. Default value "header:X-CSRF-Token".
	// Possible values:
	// - "header:<name>"
	// - "form:<name>"
	// - "query:<name>"
	TokenLookup string `json:"token_lookup"`

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

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

	// Domain of the CSRF cookie.
	// Optional. Default value none.
	CookieDomain string `json:"cookie_domain"`

	// Path of the CSRF cookie.
	// Optional. Default value none.
	CookiePath string `json:"cookie_path"`

	// Expiration time of the CSRF cookie.
	// Optional. Default value 24H.
	CookieExpires time.Time `json:"cookie_expires"`

	// Indicates if CSRF cookie is secure.
	CookieSecure bool `json:"cookie_secure"`

	// Indicates if CSRF cookie is HTTP only.
	// Optional. Default value false.
	CookieHTTPOnly bool `json:"cookie_http_only"`
}

CSRFConfig defines the config for CSRF middleware.

type GzipConfig

type GzipConfig struct {
	// Gzip compression level.
	// Optional. Default value -1.
	Level int `json:"level"`
}

GzipConfig defines the config for gzip middleware.

type JWTConfig

type JWTConfig struct {
	// Signing key to validate token.
	// Required.
	SigningKey []byte `json:"signing_key"`

	// Signing method, used to check token signing method.
	// Optional. Default value HS256.
	SigningMethod string `json:"signing_method"`

	// Context key to store user information from the token into context.
	// Optional. Default value "user".
	ContextKey string `json:"context_key"`

	// TokenLookup is a string in the form of "<source>:<name>" that is used
	// to extract token from the request.
	// Optional. Default value "header:Authorization".
	// Possible values:
	// - "header:<name>"
	// - "query:<name>"
	TokenLookup string `json:"token_lookup"`
}

JWTConfig defines the config for JWT auth middleware.

type LoggerConfig

type LoggerConfig struct {
	// Log format which can be constructed using the following tags:
	//
	// - time_rfc3339
	// - id (Request ID - Not implemented)
	// - remote_ip
	// - uri
	// - host
	// - method
	// - path
	// - referer
	// - user_agent
	// - status
	// - latency (In microseconds)
	// - latency_human (Human readable)
	// - rx_bytes (Bytes received)
	// - tx_bytes (Bytes sent)
	//
	// Example "${remote_ip} ${status}"
	//
	// Optional. Default value DefaultLoggerConfig.Format.
	Format string `json:"format"`

	// Output is a writer where logs 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 {
	// Getter is a function that gets overridden method from the request.
	// Optional. Default values MethodFromHeader(echo.HeaderXHTTPMethodOverride).
	Getter MethodOverrideGetter
}

MethodOverrideConfig defines the config for method override 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 RecoverConfig

type RecoverConfig struct {
	// Size of the stack to be printed.
	// Optional. Default value 4KB.
	StackSize int `json:"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 `json:"disable_stack_all"`

	// DisablePrintStack disables printing stack trace.
	// Optional. Default value as false.
	DisablePrintStack bool `json:"disable_print_stack"`
}

RecoverConfig defines the config for recover middleware.

type SecureConfig

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

	// ContentTypeNosniff provides protection against overriding Content-Type
	// header by setting the `X-Content-Type-Options` header.
	// Optional. Default value "nosniff".
	ContentTypeNosniff string `json:"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 `json:"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 `json:"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 `json:"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 `json:"content_security_policy"`
}

SecureConfig defines the config for secure middleware.

type StaticConfig

type StaticConfig struct {
	// Root directory from where the static content is served.
	// Required.
	Root string `json:"root"`

	// Index file for serving a directory.
	// Optional. Default value "index.html".
	Index string `json:"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 `json:"html5"`

	// Enable directory browsing.
	// Optional. Default value false.
	Browse bool `json:"browse"`
}

StaticConfig defines the config for static middleware.

type TrailingSlashConfig

type TrailingSlashConfig struct {
	// Status code to be used when redirecting the request.
	// Optional, but when provided the request is redirected using this code.
	RedirectCode int `json:"redirect_code"`
}

TrailingSlashConfig defines the config for TrailingSlash middleware.

Jump to

Keyboard shortcuts

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