From ff7e47a64e6bdf1a46dcbe7244e29ce5ebfd5fae Mon Sep 17 00:00:00 2001 From: d1slike Date: Tue, 26 Jul 2022 21:38:38 +0300 Subject: [PATCH] MSP-437 implement throttling middleware --- middleware/throttling.go | 41 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 middleware/throttling.go diff --git a/middleware/throttling.go b/middleware/throttling.go new file mode 100644 index 0000000..8abd3f8 --- /dev/null +++ b/middleware/throttling.go @@ -0,0 +1,41 @@ +package middleware + +import ( + "context" + "fmt" + "net/http" + + "github.com/pkg/errors" + "isp-gate-service/domain" + "isp-gate-service/httperrors" + "isp-gate-service/request" +) + +type Throttler interface { + AllowRateLimit(ctx context.Context, applicationId int) (*domain.RateLimitResult, error) +} + +func Throttling(throttler Throttler) Middleware { + return func(next Handler) Handler { + return HandlerFunc(func(ctx *request.Context) error { + authData, err := ctx.GetAuthData() + if err != nil { + return errors.WithMessage(err, "throttling: get auth data") + } + + result, err := throttler.AllowRateLimit(ctx.Context(), authData.ApplicationId) + if err != nil { + return errors.WithMessage(err, "throttling: allow rate limit") + } + if !result.Allow { + return httperrors.New( + http.StatusTooManyRequests, + fmt.Sprintf("rate limit has been reached, try after %dms", result.RetryAfter.Milliseconds()), + errors.Errorf("throttling: rate limit has been reached for application '%d'", authData.ApplicationId), + ) + } + + return next.Handle(ctx) + }) + } +}