Documentation
¶
Index ¶
- Constants
- Variables
- func BodyLimit(limit string) gin.HandlerFunc
- func BodyLimitWithConfig(config BodyLimitConfig) gin.HandlerFunc
- func IsWebSocket(c *gin.Context) bool
- func JWT(key interface{}) gin.HandlerFunc
- func JWTWithConfig(config JWTConfig) gin.HandlerFunc
- func Proxy(balancer ProxyBalancer) gin.HandlerFunc
- func ProxyWithConfig(config ProxyConfig) gin.HandlerFunc
- func RateLimiter(store RateLimiterStore) gin.HandlerFunc
- func RateLimiterWithConfig(config RateLimiterConfig) gin.HandlerFunc
- type BodyLimitConfig
- type Extractor
- type JWTConfig
- type JWTErrorHandler
- type JWTErrorHandlerWithContext
- type JWTSuccessHandler
- type ProxyBalancer
- type ProxyConfig
- type ProxyTarget
- type RateLimiterConfig
- type RateLimiterMemoryStore
- type RateLimiterMemoryStoreConfig
- type RateLimiterStore
- type Visitor
Constants ¶
const (
AlgorithmHS256 = "HS256"
)
Algorithms
Variables ¶
var ( ErrJWTMissing = e.NewHTTPError(http.StatusBadRequest, "missing or malformed jwt") ErrJWTInvalid = e.NewHTTPError(http.StatusUnauthorized, "invalid or expired jwt") )
Errors
var ( // ErrRateLimitExceeded denotes an error raised when rate limit is exceeded ErrRateLimitExceeded = e.NewHTTPError(http.StatusTooManyRequests, "rate limit exceeded") // ErrExtractorError denotes an error raised when extractor function is unsuccessful ErrExtractorError = e.NewHTTPError(http.StatusForbidden, "error while extracting identifier") )
errors
var ( // DefaultBodyLimitConfig is the default BodyLimit middleware config. DefaultBodyLimitConfig = BodyLimitConfig{ Skipper: pkg.DefaultSkipper, } )
var ( // DefaultJWTConfig is the default JWT auth middleware config. DefaultJWTConfig = JWTConfig{ Skipper: pkg.DefaultSkipper, SigningMethod: AlgorithmHS256, ContextKey: "user", TokenLookup: "header:" + pkg.HeaderAuthorization, AuthScheme: "Bearer", Claims: jwt.MapClaims{}, } )
var ( // DefaultProxyConfig is the default Proxy middleware config. DefaultProxyConfig = ProxyConfig{ Skipper: pkg.DefaultSkipper, ContextKey: "target", } )
var DefaultRateLimiterConfig = RateLimiterConfig{ Skipper: pkg.DefaultSkipper, IdentifierExtractor: func(ctx *gin.Context) (string, error) { id := ctx.ClientIP() return id, nil }, ErrorHandler: func(context *gin.Context, err error) error { return &e.HTTPError{ Code: ErrExtractorError.Code, Message: ErrExtractorError.Message, Internal: err, } }, DenyHandler: func(context *gin.Context, identifier string, err error) error { return &e.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
Functions ¶
func BodyLimit ¶
func BodyLimit(limit string) gin.HandlerFunc
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) gin.HandlerFunc
BodyLimitWithConfig returns a BodyLimit middleware with config. See: `BodyLimit()`.
func IsWebSocket ¶
func JWT ¶
func JWT(key interface{}) gin.HandlerFunc
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) gin.HandlerFunc
JWTWithConfig returns a JWT auth middleware with config. See: `JWT()`.
func Proxy ¶
func Proxy(balancer ProxyBalancer) gin.HandlerFunc
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) gin.HandlerFunc
ProxyWithConfig returns a Proxy middleware with config. See: `Proxy()`
func RateLimiter ¶
func RateLimiter(store RateLimiterStore) gin.HandlerFunc
RateLimiter returns a rate limiting middleware
limiterStore := middleware.NewRateLimiterMemoryStore(20)
e.GET("/rate-limited", func(c *gin.Context) {
c.String(http.StatusOK, "test")
return
}, RateLimiter(limiterStore))
func RateLimiterWithConfig ¶
func RateLimiterWithConfig(config RateLimiterConfig) gin.HandlerFunc
Types ¶
type BodyLimitConfig ¶
type BodyLimitConfig struct {
// Skipper defines a function to skip middleware.
Skipper pkg.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 JWTConfig ¶
type JWTConfig struct {
// Skipper defines a function to skip middleware.
Skipper pkg.Skipper
// BeforeFunc defines a function which is executed just before the middleware.
BeforeFunc pkg.BeforeFunc
// SuccessHandler defines a function which is executed for a valid token.
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
// Signing key to validate token. Used as fallback if SigningKeys has length 0.
// Required. This or SigningKeys.
SigningKey interface{}
// Map of signing keys to validate token with kid field usage.
// Required. This or SigningKey.
SigningKeys map[string]interface{}
// Signing method, used to check token signing method.
// 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.
// 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>"
// - "param:<name>"
// - "cookie:<name>"
// - "form:<name>"
TokenLookup string
// AuthScheme to be used in the Authorization header.
// Optional. Default value "Bearer".
AuthScheme string
// contains filtered or unexported fields
}
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 ¶
JWTSuccessHandler defines a function which is executed for a valid token.
type ProxyBalancer ¶
type ProxyBalancer interface {
AddTarget(*ProxyTarget) bool
RemoveTarget(string) bool
Next(*gin.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 pkg.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 pkg.Skipper
BeforeFunc pkg.BeforeFunc
// IdentifierExtractor uses *gin.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 *gin.Context, err error) error
// DenyHandler provides a handler to be called when RateLimiter denies access
DenyHandler func(context *gin.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)
func NewRateLimiterMemoryStoreWithConfig ¶
func NewRateLimiterMemoryStoreWithConfig(config RateLimiterMemoryStoreConfig) (store *RateLimiterMemoryStore)
type RateLimiterMemoryStoreConfig ¶
type RateLimiterMemoryStoreConfig struct {
Rate rate.Limit // Rate of requests allowed to pass as req/s
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.