{"modulePath":"github.com/acronis/go-appkit","version":"v1.38.0","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package throttle\n\nPackage throttle provides configurable middleware for throttling HTTP requests on the server side.\n\n## Constants\n\n```go\nconst (\n\tRateLimitAlgLeakyBucket   = throttleconfig.RateLimitAlgLeakyBucket\n\tRateLimitAlgSlidingWindow = throttleconfig.RateLimitAlgSlidingWindow\n)\n```\nRate-limiting algorithms.\n\n```go\nconst (\n\tZoneKeyTypeNoKey      = throttleconfig.ZoneKeyTypeNoKey\n\tZoneKeyTypeIdentity   = throttleconfig.ZoneKeyTypeIdentity\n\tZoneKeyTypeHTTPHeader = throttleconfig.ZoneKeyTypeHeader\n\tZoneKeyTypeRemoteAddr = throttleconfig.ZoneKeyTypeRemoteAddr\n)\n```\nZone key types.\n\n```go\nconst RuleLogFieldName = \"throttle_rule\"\n```\nRuleLogFieldName is a logged field that contains the name of the throttling rule.\n\n## Functions\n\n```go\nfunc InFlightLimitMiddleware(\n\tcfg *InFlightLimitZoneConfig, errDomain string, ruleName string, mc MetricsCollector,\n) (func(next http.Handler) http.Handler, error)\n```\nInFlightLimitMiddleware is a middleware that performs in-flight limiting based on the passed configuration.\n\n```go\nfunc InFlightLimitMiddlewareWithOpts(\n\tcfg *InFlightLimitZoneConfig, errDomain string, ruleName string, mc MetricsCollector, opts InFlightLimitMiddlewareOpts,\n) (func(next http.Handler) http.Handler, error)\n```\nInFlightLimitMiddlewareWithOpts is a more configurable version of InFlightLimitMiddleware.\n\n```go\nfunc MapstructureDecodeHook() mapstructure.DecodeHookFunc\n```\nMapstructureDecodeHook returns a DecodeHookFunc for mapstructure to handle custom types.\n\n```go\nfunc Middleware(cfg *Config, errDomain string, mc MetricsCollector) (func(next http.Handler) http.Handler, error)\n```\nMiddleware is a middleware that throttles incoming HTTP requests based on the passed configuration.\n\n```go\nfunc MiddlewareWithOpts(\n\tcfg *Config, errDomain string, mc MetricsCollector, opts MiddlewareOpts,\n) (func(next http.Handler) http.Handler, error)\n```\nMiddlewareWithOpts is a more configurable version of Middleware.\n\n```go\nfunc NewPrometheusMetrics() *throttleconfig.PrometheusMetrics\n```\nNewPrometheusMetrics creates a new instance of PrometheusMetrics.\n\n```go\nfunc NewPrometheusMetricsWithOpts(opts throttleconfig.PrometheusMetricsOpts) *throttleconfig.PrometheusMetrics\n```\nNewPrometheusMetricsWithOpts creates a new instance of PrometheusMetrics with the provided options.\n\n```go\nfunc RateLimitMiddleware(\n\tcfg *RateLimitZoneConfig, errDomain string, ruleName string, mc MetricsCollector,\n) (func(next http.Handler) http.Handler, error)\n```\nRateLimitMiddleware is a middleware that performs rate limiting based on the passed configuration.\n\n```go\nfunc RateLimitMiddlewareWithOpts(\n\tcfg *RateLimitZoneConfig, errDomain string, ruleName string, mc MetricsCollector, opts RateLimitMiddlewareOpts,\n) (func(next http.Handler) http.Handler, error)\n```\nRateLimitMiddlewareWithOpts is a more configurable version of RateLimitMiddleware.\n\n## Types\n\n```go\ntype Config struct {\n\t// RateLimitZones contains rate limiting zones.\n\t// Key is a zone's name, and value is a zone's configuration.\n\tRateLimitZones map[string]RateLimitZoneConfig `mapstructure:\"rateLimitZones\" yaml:\"rateLimitZones\" json:\"rateLimitZones\"`\n\n\t// InFlightLimitZones contains in-flight limiting zones.\n\t// Key is a zone's name, and value is a zone's configuration.\n\tInFlightLimitZones map[string]InFlightLimitZoneConfig `mapstructure:\"inFlightLimitZones\" yaml:\"inFlightLimitZones\" json:\"inFlightLimitZones\"` //nolint:lll // struct tags must be on one line\n\n\t// Rules contains list of so-called throttling rules.\n\t// Basically, throttling rule represents a route (or multiple routes),\n\t// and rate/in-flight limiting zones based on which all matched HTTP requests will be throttled.\n\tRules []RuleConfig `mapstructure:\"rules\" yaml:\"rules\" json:\"rules\"`\n\t// contains filtered or unexported fields\n}\n```\nConfig represents a configuration for throttling of HTTP requests on the server side. Configuration can be loaded in different formats (YAML, JSON) using config.Loader, viper, or with json.Unmarshal/yaml.Unmarshal functions directly.\n\n```go\nfunc NewConfig(options ...ConfigOption) *Config\n```\nNewConfig creates a new instance of the Config.\n\n```go\nfunc NewConfigWithKeyPrefix(keyPrefix string) *Config\n```\nNewConfigWithKeyPrefix creates a new instance of the Config with a key prefix. This prefix will be used by config.Loader.\n\nDeprecated: use NewConfig with WithKeyPrefix instead.\n\n```go\nfunc (c *Config) KeyPrefix() string\n```\nKeyPrefix returns a key prefix with which all configuration parameters should be presented. Implements config.KeyPrefixProvider interface.\n\n```go\nfunc (c *Config) Set(dp config.DataProvider) error\n```\nSet sets throttling configuration values from config.DataProvider. Implements config.Config interface.\n\n```go\nfunc (c *Config) SetProviderDefaults(_ config.DataProvider)\n```\nSetProviderDefaults sets default configuration values for logger in config.DataProvider. Implements config.Config interface.\n\n```go\nfunc (c *Config) Validate() error\n```\nValidate validates configuration.\n\n```go\ntype ConfigOption func(*configOptions)\n```\nConfigOption is a type for functional options for the Config.\n\n```go\nfunc WithKeyPrefix(keyPrefix string) ConfigOption\n```\nWithKeyPrefix returns a ConfigOption that sets a key prefix for parsing configuration parameters. This prefix will be used by config.Loader.\n\n```go\ntype InFlightLimitMiddlewareOpts struct {\n\t// GetKeyIdentity is a function that returns identity string representation.\n\t// The returned string is used as a key for zone when key.type is \"identity\".\n\tGetKeyIdentity func(r *http.Request) (key string, bypass bool, err error)\n\n\t// InFlightLimitOnReject is a callback that is called for rejecting HTTP request when the in-flight limit is exceeded.\n\tInFlightLimitOnReject middleware.InFlightLimitOnRejectFunc\n\n\t// RateLimitOnRejectInDryRun is a callback that is called for rejecting HTTP request in the dry-run mode\n\t// when the in-flight limit is exceeded.\n\tInFlightLimitOnRejectInDryRun middleware.InFlightLimitOnRejectFunc\n\n\t// RateLimitOnError is a callback that is called in case of any error that may occur during the in-flight limiting.\n\tInFlightLimitOnError middleware.InFlightLimitOnErrorFunc\n}\n```\n\n```go\ntype InFlightLimitZoneConfig struct {\n\tZoneConfig         `mapstructure:\",squash\" yaml:\",inline\"`\n\tInFlightLimit      int                 `mapstructure:\"inFlightLimit\" yaml:\"inFlightLimit\" json:\"inFlightLimit\"`\n\tBacklogLimit       int                 `mapstructure:\"backlogLimit\" yaml:\"backlogLimit\" json:\"backlogLimit\"`\n\tBacklogTimeout     config.TimeDuration `mapstructure:\"backlogTimeout\" yaml:\"backlogTimeout\" json:\"backlogTimeout\"`\n\tResponseRetryAfter config.TimeDuration `mapstructure:\"responseRetryAfter\" yaml:\"responseRetryAfter\" json:\"responseRetryAfter\"`\n}\n```\nInFlightLimitZoneConfig represents zone configuration for in-flight limiting.\n\n```go\nfunc (c *InFlightLimitZoneConfig) Validate() error\n```\nValidate validates zone configuration for in-flight limiting.\n\n```go\ntype MetricsCollector = throttleconfig.MetricsCollector\n```\nMetricsCollector represents a collector of metrics for rate/in-flight limiting rejects.\n\n```go\ntype MiddlewareOpts struct {\n\t// GetKeyIdentity is a function that returns identity string representation.\n\t// The returned string is used as a key for zone when key.type is \"identity\".\n\tGetKeyIdentity func(r *http.Request) (key string, bypass bool, err error)\n\n\t// RateLimitOnReject is a callback called for rejecting HTTP request when the rate limit is exceeded.\n\tRateLimitOnReject middleware.RateLimitOnRejectFunc\n\n\t// RateLimitOnRejectInDryRun is a callback called for rejecting HTTP request in the dry-run mode\n\t// when the rate limit is exceeded.\n\tRateLimitOnRejectInDryRun middleware.RateLimitOnRejectFunc\n\n\t// RateLimitOnError is a callback called in case of any error that may occur during the rate limiting.\n\tRateLimitOnError middleware.RateLimitOnErrorFunc\n\n\t// InFlightLimitOnReject is a callback called for rejecting HTTP request when the in-flight limit is exceeded.\n\tInFlightLimitOnReject middleware.InFlightLimitOnRejectFunc\n\n\t// RateLimitOnRejectInDryRun is a callback called for rejecting HTTP request in the dry-run mode\n\t// when the in-flight limit is exceeded.\n\tInFlightLimitOnRejectInDryRun middleware.InFlightLimitOnRejectFunc\n\n\t// RateLimitOnError is a callback called in case of any error that may occur during the in-flight limiting.\n\tInFlightLimitOnError middleware.InFlightLimitOnErrorFunc\n\n\t// Tags is a list of tags for filtering throttling rules from the config. If it's empty, all rules can be applied.\n\tTags []string\n\n\t// BuildHandlerAtInit determines where the final handler will be constructed.\n\t// If true, it will be done at the initialization step (i.e., in the constructor),\n\t// false (default) - right in the ServeHTTP() method (gorilla/mux case).\n\tBuildHandlerAtInit bool\n}\n```\nMiddlewareOpts represents an options for Middleware.\n\n```go\nfunc (opts MiddlewareOpts) InFlightLimitOpts() InFlightLimitMiddlewareOpts\n```\nInFlightLimitOpts returns options for constructing in-flight limiting middleware.\n\n```go\nfunc (opts MiddlewareOpts) RateLimitOpts() RateLimitMiddlewareOpts\n```\nRateLimitOpts returns options for constructing rate limiting middleware.\n\n```go\ntype PrometheusMetrics = throttleconfig.PrometheusMetrics\n```\nPrometheusMetrics represents a collector of Prometheus metrics for rate/in-flight limiting rejects.\n\n```go\ntype PrometheusMetricsOpts = throttleconfig.PrometheusMetricsOpts\n```\nPrometheusMetricsOpts represents options for PrometheusMetrics.\n\n```go\ntype RateLimitMiddlewareOpts struct {\n\t// GetKeyIdentity is a function that returns identity string representation.\n\t// The returned string is used as a key for zone when key.type is \"identity\".\n\tGetKeyIdentity func(r *http.Request) (key string, bypass bool, err error)\n\n\t// RateLimitOnReject is a callback that is called for rejecting HTTP request when the rate limit is exceeded.\n\tRateLimitOnReject middleware.RateLimitOnRejectFunc\n\n\t// RateLimitOnRejectInDryRun is a callback that is called for rejecting HTTP request in the dry-run mode\n\t// when the rate limit is exceeded.\n\tRateLimitOnRejectInDryRun middleware.RateLimitOnRejectFunc\n\n\t// RateLimitOnError is a callback that is called in case of any error that may occur during the rate limiting.\n\tRateLimitOnError middleware.RateLimitOnErrorFunc\n}\n```\nRateLimitMiddlewareOpts represents an options for RateLimitMiddleware.\n\n```go\ntype RateLimitRetryAfterValue = throttleconfig.RateLimitRetryAfterValue\n```\nRateLimitRetryAfterValue represents structured retry-after value for rate limiting.\n\n```go\ntype RateLimitValue = throttleconfig.RateLimitValue\n```\nRateLimitValue represents value for rate limiting.\n\n```go\ntype RateLimitZoneConfig struct {\n\tZoneConfig         `mapstructure:\",squash\" yaml:\",inline\"`\n\tAlg                string                   `mapstructure:\"alg\" yaml:\"alg\" json:\"alg\"`\n\tRateLimit          RateLimitValue           `mapstructure:\"rateLimit\" yaml:\"rateLimit\" json:\"rateLimit\"`\n\tBurstLimit         int                      `mapstructure:\"burstLimit\" yaml:\"burstLimit\" json:\"burstLimit\"`\n\tBacklogLimit       int                      `mapstructure:\"backlogLimit\" yaml:\"backlogLimit\" json:\"backlogLimit\"`\n\tBacklogTimeout     config.TimeDuration      `mapstructure:\"backlogTimeout\" yaml:\"backlogTimeout\" json:\"backlogTimeout\"`\n\tResponseRetryAfter RateLimitRetryAfterValue `mapstructure:\"responseRetryAfter\" yaml:\"responseRetryAfter\" json:\"responseRetryAfter\"`\n}\n```\nRateLimitZoneConfig represents zone configuration for rate limiting.\n\n```go\nfunc (c *RateLimitZoneConfig) Validate() error\n```\nValidate validates zone configuration for rate limiting.\n\n```go\ntype RuleConfig struct {\n\t// Alias is an alternative name for the rule. It will be used as a label in metrics.\n\tAlias string `mapstructure:\"alias\" yaml:\"alias\" json:\"alias\"`\n\n\t// Routes contains a list of routes (HTTP verb + URL path) for which the rule will be applied.\n\tRoutes []restapi.RouteConfig `mapstructure:\"routes\" yaml:\"routes\" json:\"routes\"`\n\n\t// ExcludedRoutes contains list of routes (HTTP verb + URL path) to be excluded from throttling limitations.\n\t// The following service endpoints fit should typically be added to this list:\n\t// - healthcheck endpoint serving as readiness probe\n\t// - status endpoint serving as liveness probe\n\tExcludedRoutes []restapi.RouteConfig `mapstructure:\"excludedRoutes\" yaml:\"excludedRoutes\" json:\"excludedRoutes\"`\n\n\t// Tags is useful when the different rules of the same config should be used by different middlewares.\n\t// As example let's suppose we would like to have 2 different throttling rules:\n\t// 1) for absolutely all requests;\n\t// 2) for all identity-aware (authorized) requests.\n\t// In the code, we will have 2 middlewares that will be executed on the different steps of the HTTP request serving,\n\t// and each one should do only its own throttling.\n\t// We can achieve this using different tags for rules and passing needed tag in the MiddlewareOpts.\n\t// Tags can also be specified per zone (on RateLimits and InFlightLimits items) for more fine-grained control.\n\tTags TagsList `mapstructure:\"tags\" yaml:\"tags\" json:\"tags\"`\n\n\t// RateLimits contains a list of the rate limiting zones that are used in the rule.\n\tRateLimits []RuleRateLimit `mapstructure:\"rateLimits\" yaml:\"rateLimits\" json:\"rateLimits\"`\n\n\t// InFlightLimits contains a list of the in-flight limiting zones that are used in the rule.\n\tInFlightLimits []RuleInFlightLimit `mapstructure:\"inFlightLimits\" yaml:\"inFlightLimits\" json:\"inFlightLimits\"`\n}\n```\nRuleConfig represents configuration for throttling rule.\n\n```go\nfunc (c *RuleConfig) Name() string\n```\nName returns throttling rule name.\n\n```go\nfunc (c *RuleConfig) Validate(\n\trateLimitZones map[string]RateLimitZoneConfig, inFlightLimitZones map[string]InFlightLimitZoneConfig,\n) error\n```\nValidate validates throttling rule configuration.\n\n```go\ntype RuleInFlightLimit = throttleconfig.RuleInFlightLimit\n```\nRuleInFlightLimit represents rule's in-flight limiting parameters.\n\n```go\ntype RuleRateLimit = throttleconfig.RuleRateLimit\n```\nRuleRateLimit represents rule's rate limiting parameters.\n\n```go\ntype TagsList = throttleconfig.TagsList\n```\nTagsList represents a list of tags.\n\n```go\ntype ZoneConfig struct {\n\tKey                ZoneKeyConfig `mapstructure:\"key\" yaml:\"key\" json:\"key\"`\n\tMaxKeys            int           `mapstructure:\"maxKeys\" yaml:\"maxKeys\" json:\"maxKeys\"`\n\tResponseStatusCode int           `mapstructure:\"responseStatusCode\" yaml:\"responseStatusCode\" json:\"responseStatusCode\"`\n\tDryRun             bool          `mapstructure:\"dryRun\" yaml:\"dryRun\" json:\"dryRun\"`\n\tIncludedKeys       []string      `mapstructure:\"includedKeys\" yaml:\"includedKeys\" json:\"includedKeys\"`\n\tExcludedKeys       []string      `mapstructure:\"excludedKeys\" yaml:\"excludedKeys\" json:\"excludedKeys\"`\n}\n```\nZoneConfig represents a basic zone configuration.\n\n```go\nfunc (c *ZoneConfig) Validate() error\n```\nValidate validates zone configuration.\n\n```go\ntype ZoneKeyConfig = throttleconfig.ZoneKeyConfig\n```\nZoneKeyConfig represents a configuration of zone's key.\n\n```go\ntype ZoneKeyType = throttleconfig.ZoneKeyType\n```\nZoneKeyType is a type of keys zone.\n\n","path":"github.com/acronis/go-appkit/httpserver/middleware/throttle","name":"throttle","synopsis":"Package throttle provides configurable middleware for throttling HTTP requests on the server side.","isRedistributable":true}
