package
1.12.6
Repository: https://github.com/go-dev-frame/sponge.git
Documentation: pkg.go.dev

# README

ratelimit

Adaptive rate limit, only available for linux systems.


Example of use

gin ratelimit middleware

import (
	rl "github.com/go-dev-frame/sponge/pkg/shield/ratelimit"
)

func RateLimit(opts ...RateLimitOption) gin.HandlerFunc {
	o := defaultRatelimitOptions()
	o.apply(opts...)
	limiter := rl.NewLimiter(
		rl.WithWindow(o.window),
		rl.WithBucket(o.bucket),
		rl.WithCPUThreshold(o.cpuThreshold),
		rl.WithCPUQuota(o.cpuQuota),
	)

	return func(c *gin.Context) {
		done, err := limiter.Allow()
		if err != nil {
			response.Output(c, http.StatusTooManyRequests, err.Error())
			c.Abort()
			return
		}

		c.Next()

		done(rl.DoneInfo{Err: c.Request.Context().Err()})
	}
}

grpc ratelimit interceptor

import (
	rl "github.com/go-dev-frame/sponge/pkg/shield/ratelimit"
)


func UnaryServerRateLimit(opts ...RatelimitOption) grpc.UnaryServerInterceptor {
	o := defaultRatelimitOptions()
	o.apply(opts...)
	limiter := rl.NewLimiter(
		rl.WithWindow(o.window),
		rl.WithBucket(o.bucket),
		rl.WithCPUThreshold(o.cpuThreshold),
		rl.WithCPUQuota(o.cpuQuota),
	)

	return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
		done, err := limiter.Allow()
		if err != nil {
			return nil, errcode.StatusLimitExceed.ToRPCErr(err.Error())
		}

		reply, err := handler(ctx, req)
		done(rl.DoneInfo{Err: err})
		return reply, err
	}
}

# Functions

NewLimiter returns a bbr limiter.
WithBucket with bucket ize.
WithCPUQuota with real cpu quota(if it can not collect from process correct);.
WithCPUThreshold with cpu threshold;.
WithWindow with window size.

# Variables

ErrLimitExceed is returned when the rate limiter is triggered and the request is rejected due to limit exceeded.

# Structs

BBR implements bbr-like limiter.
DoneInfo is done info.
Stat contains the metrics snapshot of bbr.

# Interfaces

Limiter is a rate limiter.

# Type aliases

DoneFunc is done function.
No description provided by the author