middleware

package
v1.0.5 Latest Latest
Warning

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

Go to latest
Published: Apr 12, 2021 License: MIT Imports: 24 Imported by: 0

Documentation

Index

Constants

View Source
const ContextBindModels = "bind_models"
View Source
const ContextIP = "ip"

Variables

View Source
var (
	ErrJWTMissing = gof.ErrBadRequest.SetMessage("missing or malformed jwt")
	ErrJWTInvalid = gof.ErrUnauthorized.SetMessage("invalid or expired jwt")
)
View Source
var (
	ErrKeyAuthMissing = gof.ErrBadRequest.SetMessage("missing or malformed key")
	ErrKeyAuthInvalid = gof.ErrUnauthorized.SetMessage("invalid key")
)
View Source
var (
	// ErrLimitExceeded denotes an error raised when rate limit is exceeded
	ErrLimitExceeded   = gof.ErrTooManyRequests.SetMessage("rate limit exceeded")
	ErrIdentifierError = gof.ErrForbidden.SetMessage("error while extracting identifier")
)
View Source
var DefaultCORSConfig = CORSConfig{
	AllowOrigins: []string{"*"},
	AllowMethods: []string{http.MethodGet, http.MethodHead, http.MethodPut, http.MethodPatch, http.MethodPost, http.MethodDelete},
}

Functions

func Bind

func Bind(binder gof.Binder, l gof.Logger, model ...interface{}) mux.MiddlewareFunc

func CORS

func CORS(cfg CORSConfig, logger gof.Logger) mux.MiddlewareFunc

func Chain

func Chain(handler ...mux.MiddlewareFunc) mux.MiddlewareFunc

func Gzip

func Gzip(cfg GzipConfig, logger gof.Logger) mux.MiddlewareFunc

func IP

func IP() mux.MiddlewareFunc

func JWTAuth

func JWTAuth(cfg JWTAuthConfig, logger gof.Logger) mux.MiddlewareFunc

func KeyAuth

func KeyAuth(cfg KeyAuthConfig, logger gof.Logger) mux.MiddlewareFunc

func Limiter

func Limiter(cfg LimiterConfig, logger gof.Logger) mux.MiddlewareFunc

func LimiterWithStore

func LimiterWithStore(store LimiterStore, logger gof.Logger) mux.MiddlewareFunc

func Logger

func Logger(logger gof.Logger, notlogged ...string) mux.MiddlewareFunc

func Recover

func Recover(cfg RecoverConfig, logger gof.Logger) mux.MiddlewareFunc

func RemoteAuth

func RemoteAuth(cfg RemoteAuthConfig, logger gof.Logger) mux.MiddlewareFunc

func ValidateFromContext

func ValidateFromContext(contextKey string, l gof.Logger) mux.MiddlewareFunc

Types

type CORSConfig

type CORSConfig struct {
	// AllowOrigin defines a list of origins that may access the resource.
	// Optional. Default value []string{"*"}.
	AllowOrigins []string `yaml:"allow_origins" json:"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.
	// Optional.
	AllowOriginFunc func(origin string) (bool, error) `yaml:"allow_origin_func" json:"allow_origin_func"`

	// 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 `yaml:"allow_methods" json:"allow_methods"`

	// AllowHeaders defines a list of request headers that can be used when
	// making the actual request. This is in response to a preflight request.
	// Optional. Default value []string{}.
	AllowHeaders []string `yaml:"allow_headers" 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 `default:"false" yaml:"allow_credentials" json:"allow_credentials"`

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

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

type ErrorField

type ErrorField struct {
	Field   string `json:"field"`
	Message string `json:"message"`
}

type GzipConfig

type GzipConfig struct {
	Compression int `default:"5"`
}

type JWTAuthConfig

type JWTAuthConfig struct {
	// Signing key to validate token. Used as fallback if SigningKeys has length 0.
	// Required. This or SigningKeys.
	SigningKey string `yaml:"signing_key" json:"signing_key"`

	// Map of signing keys to validate token with kid field usage.
	// Required. This or SigningKey.
	SigningKeys map[string]string `yaml:"signing_keys" json:"signing_keys"`

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

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

	// Claims are extendable claims data defining token content.
	// Optional. Default value jwt.MapClaims
	Claims jwt.Claims

	// 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>"
	// - "cookie:<name>"
	// - "form:<name>"
	TokenLookup string `default:"header:Authorization" yaml:"token_lookup" json:"token_lookup"`

	// AuthScheme to be used in the Authorization header.
	// Optional. Default value "Bearer".
	AuthScheme string `default:"Bearer" yaml:"auth_scheme" json:"auth_scheme"`
	// contains filtered or unexported fields
}

type KeyAuthConfig

type KeyAuthConfig struct {
	// KeyLookup is a string in the form of "<source>:<name>" that is used
	// to extract key from the request.
	// Optional. Default value "header:Authorization".
	// Possible values:
	// - "header:<name>"
	// - "query:<name>"
	// - "form:<name>"
	KeyLookup string `default:"header:Authorization" yaml:"key_lookup" json:"key_lookup"`

	// AuthScheme to be used in the Authorization header.
	// Optional. Default value "Bearer".
	AuthScheme string `default:"Bearer" yaml:"auth_scheme" json:"auth_scheme"`

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

type KeyAuthValidator

type KeyAuthValidator func(string, context.Context) (context.Context, error)

KeyAuthValidator defines a function to validate Auth credentials.

type LimiterConfig

type LimiterConfig struct {
	Rate  int           `default:"10"`
	Burst int           `default:"2"`
	TTL   time.Duration `default:"10m"`
}

type LimiterMemoryStore

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

func NewLimiterMemoryStore

func NewLimiterMemoryStore(cfg LimiterConfig) (store *LimiterMemoryStore)

NewLimiterMemoryStore returns an instance of LimiterMemoryStore 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.NewLimiterMemoryStore(
	middleware.LimiterConfig{Rate: 50, Burst: 200, TTL: 5 * time.Minutes},
)

func (*LimiterMemoryStore) Allow

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

Allow implements LimiterStore.Allow

type LimiterStore

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

type RecoverConfig

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

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

type RemoteAuthConfig

type RemoteAuthConfig struct {
	Verify struct {
		URL     string        `required:"true"`
		Method  string        `default:"GET"`
		Timeout time.Duration `default:"5s"`
	}
	KeyLookup        string `default:"header:Authorization" yaml:"key_lookup" json:"key_lookup"`
	AuthScheme       string `default:"Bearer" yaml:"auth_scheme" json:"auth_scheme"`
	ContextUserKey   string `default:"user" yaml:"context_user_key" json:"context_user_key"`
	ContextUserIDKey string `default:"user_id" yaml:"context_user_id_key" json:"context_user_id_key"`
}

type RemoteUser

type RemoteUser struct {
	ID       string `json:"id"`
	Username string `json:"username"`
}

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